c - pthread 中函数的参数数量

标签 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;
}

正如你所见,pthread_create() 中的 print_hello 没有参数,但是在定义中,它看起来像 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;
}

现在我收到此错误:

too few arguments to function print_hello

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

最佳答案

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;
}

关于c - pthread 中函数的参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734777/

相关文章:

c++ - 让主程序等待线程完成

c - 将结构作为 void* 指针传递时初始化程序无效

c - PortAudio 的 PaStreamFinishedCallback 的安全操作

C++ PTHREADS - 无效的转换 void*(*)() 到 void*(*)(void*)

c - 如果我从一个函数返回而不调用 pthread_mutex_unlock 会发生什么?

c - 为什么我不能在内联汇编中使用两个以上的寄存器?

php - pthreads 在 React/Ratchet 中无法按预期工作

objective-c - @encode 编译器指令在 Objective-C 中是如何实现的?

c - WBINVD指令使用

c - 分配二维数组后字符串被截断(已编辑)