有人可以解释为什么我需要使用void * sum_thread(void * data)原型吗?

时间:2017-02-23 13:52:40

标签: c multithreading

void * sum_thread(void *data)
{
}

pthread_create(&thread_id[i], NULL, sum_thread, &arrdata[i]);

2 个答案:

答案 0 :(得分:1)

这是因为这是由pthreads API的设计者选择的返回值类型(void *)和参数列表(单个void *)的组合(pthread_create()所属)。

使用此API启动线程的所有程序都需要为其提供具有该精确原型的线程函数。您可以阅读文档(如the manual page)以了解有关此调用如何工作的更多信息。

这是一种在C中表示“任何数据”的通用方式。

答案 1 :(得分:0)

因为这是pthreads所期望的函数指针格式,所以你的回调函数必须具有该格式。没有什么可以理解的,它只是POSIX标准规定的东西。

man pthread_create给出:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

您是否会传递任何其他类型的函数指针,它会违反C标准和POSIX标准,并且您调用未定义的行为。