pthread 中函数的参数数量

mah*_*ood 2 c pthreads

在 pthread 的 hello world 示例中指出:

#include <pthread.h>
#include <stdio.h>

void * print_hello(void *arg)
{
  printf("Hello world!\n");
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t thr;
  if(pthread_create(&thr, NULL, &print_hello, NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }

  if(pthread_join(thr, NULL))
  {
    printf("Could not join thread\n");
    return -1;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到print_hellopthread_create(),没有参数,但是在定义中,它看起来像void * print_hello(void *arg)

这意味着什么?

现在假设我有这个实现

void * print_hello(int a, void *);
int main(int argc, char **argv)
{
  pthread_t thr;
  int a = 10;
  if(pthread_create(&thr, NULL, &print_hello(a), NULL))
  {
    printf("Could not create thread\n");
    return -1;
  }
  ....
  return 0;
}
void * print_hello(int a, void *arg)
{
  printf("Hello world and %d!\n", a);
  return NULL;
}
Run Code Online (Sandbox Code Playgroud)

现在我得到这个错误:

too few arguments to function print_hello
Run Code Online (Sandbox Code Playgroud)

那么我该如何解决这个问题呢?

Mos*_*faR 5

pthread将一个类型的参数传递void *给线程函数,因此您可以传递一个指向任何类型的数据的指针作为pthread_create函数的第四个参数,请查看下面修复代码的示例。

void * print_hello(void *);
int main(int argc, char **argv)
{
    pthread_t thr;
    int a = 10;
    if(pthread_create(&thr, NULL, &print_hello, (void *)&a))
    {
        printf("Could not create thread\n");
        return -1;
    }
    ....
    return 0;
}

void * print_hello(void *arg)
{
    int a = (int)*arg;
    printf("Hello world and %d!\n", a);
    return NULL;
}
Run Code Online (Sandbox Code Playgroud)

  • @mahmood:是的,只有一个。如果您想传递不止一件事,请创建一个结构或一个类。此外,此代码具有竞争条件(实际上,不会在此特定实例中造成任何问题),因为它将一个线程中的局部变量的地址传递到另一个线程。如果函数在线程尝试访问数据之前返回,您将得到未定义的结果,甚至包括垃圾数据或分段违规。由于所讨论的函数是 main 函数,因此从它返回将杀死程序,因此在这种特定情况下它是没有意义的。 (2认同)