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

How does this multiple void pointers function work?

我有一个关于在 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

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

pthread_function (void*)(i)

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

pthread_function((void*)i)

或者可以这样理解:

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

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

你最好再搜索一下创建线程的正确示例。