c - 这个多空指针函数是如何工作的?

标签 c pointers void-pointers

我有一个关于在 C 中创建线程的示例代码。在我创建线程的部分,我不明白所有 void 指针的用途,以及它们的作用。

void* pthread_function(int thread_id) {
    pthread_mutex_lock(&mutex);
    printf("I'm thread number %d in mutual exclusión\n",thread_id);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}
int main(int argc,char** argv) {
    // Init mutex
    pthread_mutex_init(&mutex,NULL);
    // Create threads
    pthread_t thread[NUM_THREADS];
    long int i;
    for (i=0;i<NUM_THREADS;++i) {
        pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function (void*)(i));
    }

}

指针在这里是如何工作的?

pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function (void*)(i));

感谢您的帮助。

最佳答案

线程函数应该具有以下签名:

void *thread_func(void *thread_param);

如果你有这样的函数,你可以用它创建一个线程,而不会出现这样的转换困惑:

void *thread_func(void *thread_param)
{
  printf("Success!\n");
  return NULL;
}

...
pthread_t thread_var;
int param = 42;
int result = pthread_create(&thread_var, NULL, thread_func, &param);

不幸的是,您示例中的线程函数没有正确的签名。 因此,作者决定不修复它,而是搞乱奇怪的类型转换。

函数的类型是(void*(*)(void*))。作者试图通过转换线程函数来达到错误的目的:

(void* (*)(void*))pthread_function

但随后引入了另一个错误:不是函数地址被强制转换而是函数被调用并且返回值被用于强制转换:

pthread_function (void*)(i)

这甚至无法编译,因为它是一个语法错误。应该是

pthread_function((void*)i)

或者它可以是这样的:

pthread_create(thread+i,NULL,(void* (*)(void*))pthread_function, (void*)(i));

但无论如何这都是错误的,这并不重要。

您最好再次搜索创建线程的正确示例。

关于c - 这个多空指针函数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894536/

相关文章:

c - 死亡循环,也许是 scanf

c++ - const 成员函数中指向 this 的非常量指针

c - 如何检查 void* 指针是否可以安全地转换为其他内容?

c++ - 在 C 中我可以将 void* 分配给 char* 但在 C++ 中不行

c++ void *到函数的参数

c++ - 我可以使用 NPAPI 在一个 DLL 中创建多个插件吗?

c - system() 的返回值不是执行程序的返回值

C 返回 double 结构

python - 为什么同一行声明的两个类对象指向一个对象?

c - 为什么在将整数分配给指针时最好使用强制转换?