Kir*_*ira 5 c multithreading pthreads
在c中,我们创建一个线程,如下所示:
void * run(void * arg){
printf("hello world\n");
}
int main(){
pthread_t thread;
int a = pthread_create(&thread, NULL, run, (void*)0);
}
Run Code Online (Sandbox Code Playgroud)
但如果我声明运行为,它将不起作用
void run(){}
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我将其强制转换(void *)为 的参数pthread_create,则效果很好。因此它只接受返回类型为 的函数(void *)。
为什么?
谢谢 !
线程函数必须声明为返回,void *因为线程库需要这样的返回值,并将其存储到pthread_join()线程终止后指定的位置。
如果您不需要任何线程返回值,您可以只使用return 0;.
在我的系统上,man pthread_create说:
如果
start_routine返回,效果就好像隐式调用pthread_exit(),使用 的返回值start_routine作为退出状态。
该返回值可通过以下函数获得pthread_join():
pthread_join()使用非 NULL参数从成功调用返回时value_ptr,终止线程传递给的值pthread_exit()存储在 引用的位置中value_ptr。