3

根据 pthread_create 手册页,该函数的参数是:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

关于 void *arg,我只是想知道是否可以向它传递多个参数,因为我编写的函数需要 2 个参数。

4

3 回答 3

4

与您一起void*,您可以传递您选择的结构:

struct my_args {
  int arg1;
  double arg2;
};

这有效地允许您传入任意参数。您的线程启动例程除了解包那些调用真正的线程启动例程(它本身可能来自该结构)之外什么也不能做。

于 2013-03-06T22:51:58.363 回答
1

创建一个结构并重写您的函数以仅采用 1 个参数并在结构内传递两个参数。

代替

thread_start(int a, int b) {

采用

typedef struct ts_args {
   int a;
   int b;
} ts_args;

thread_start(ts_args *args) {
于 2013-03-06T22:53:16.240 回答
1

使用结构和malloc. 例如

struct 
{
   int x;
   int y;
   char str[10];
} args;

args_for_thread = malloc(sizeof(args));

args_for_thread->x = 5;

... etc

然后args_for_thread用作(使用从 void* 到 args* 的强制转换)的参数argspthread_create由该线程来释放内存。

于 2013-03-06T22:53:32.200 回答