【问题标题】:Create pthread with the function of multiple arguments使用多参数函数创建 pthread
【发布时间】:2013-11-11 22:27:06
【问题描述】:

如果我要为以下函数创建一个 pthread。

假设一切都已正确申报。

pthread_create(&threadId, &attr, (void * (*)(void*))function, //what should be the arguments for here??);
int a = 0;
int b = 1;
//c and d are global variables.

void function(int a, int b){
    c = a;
    d = b;
}

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    这不起作用。 function() 必须只接受一个参数。这就是你必须这样做的原因:

    (void * ()(void))

    你告诉你的编译器“不,说真的,这个函数只接受一个参数”,当然它没有。

    您必须做的是传递一个参数(比如指向结构的指针),它可以为您提供所需的信息。

    编辑:示例见此处:number of arguments for a function in pthread

    【讨论】:

      【解决方案2】:

      pthread 线程函数总是采用一个void * 参数并返回一个void * 值。如果要传递两个参数,则必须将它们包装在 struct 中 - 例如:

      struct thread_args {
          int a;
          int b;
      };
      
      void *function(void *);
      
      struct thread_args *args = malloc(sizeof *args);
      
      if (args != NULL)
      {
          args->a = 0;
          args->b = 1;
          pthread_create(&threadId, &attr, &function, args);
      }
      

      对于线程函数本身:

      void *function(void *argp)
      {
          struct thread_args *args = argp;
      
          int c = args->a;
          int d = args->b;
      
          free(args);
      
          /* ... */
      

      您不需要使用malloc()free(),但您必须以某种方式确保原始线程不会取消分配或重新使用线程参数struct,直到被调用线程完成它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多