C++ 错误创建 n 个 pthreads-

C++ erroring creating n pthreads-

在本应采用 int k 并创建 k 个 pthreads 的函数中出现以下错误:

cse451.cpp:95:60: 错误:从‘void*’到‘pthread_t* {aka long unsigned int*}’的无效转换[-fpermissive]

cse451.cpp:97:54:错误:void 表达式的使用无效

我觉得它与 foo() 函数有关(此时它仅用作占位符 foo(){} )

相关代码如下(第95行是pthread_t *threads……第97行是err=pthread_create.....)

void createThreads(int k){
int numThreads = k;
int i = 0;
int err = 0;
pthread_t *threads = malloc(sizeof(pthread_t) * numThreads);
for(i = 0;i<numThreads;i++){
    err = pthread_create(&threads[i], NULL, foo(), NULL);
    if(err != 0){
        printf("error creating thread\n");
    }
}
}

void foo(){}

第一个问题是您正在尝试使用 C++ 编译器编译 C。本次转换:

pthread_t *threads = malloc(sizeof(pthread_t) * numThreads);

从由 malloc 编辑的无类型 void* 指针 return 到类型化 pthread_t* 指针,在 C 中是允许的,但需要在 C++ 中强制转换。

pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));

但如果这是 C++,你最好使用

std::vector<pthread_t> threads(numThreads);

所以你不需要自己处理内存。您可能还想看看标准线程库,它比 POSIX 线程更友好。

第二个问题是pthread_create的参数应该是函数指针foo,而不是调用函数foo()的结果。您的函数类型也有误;它必须 return void*

void *foo(void*);

它将您提供的参数传递给 pthread_create(在本例中为 NULL),并且 return 是一个指向您加入线程时想要接收的任何内容的指针(return NULL; 如果你不想 return 任何东西)。

cse451.cpp:97:54: error: invalid use of void expression

您需要将foo()的函数指针传递给pthread_create(),而不是调用函数

 pthread_create(&threads[i], NULL, foo, NULL); // << See the parenthesis are
                                               //    omitted

至少有两处错误:

  • 您需要将指向函数的指针传递给 pthread_create 的第三个参数,而不是您打算在线程中 运行 调用的函数的结果。
  • 函数的原型应该是这样的

    void *f(void *);

    即它应该接受一个指向 void 的指针作为参数,return 一个指向 void 的指针。

您对 pthread_create 的调用应如下所示:

void *foo(void*);
err = pthread_create(&threads[i], NULL, foo, NULL);