C 关于pthread\u t指针转换的警告
我编写此测试代码是为了尝试将thread2的pthread_t传递给thread1,并编写让C 关于pthread\u t指针转换的警告,c,pthreads,C,Pthreads,我编写此测试代码是为了尝试将thread2的pthread_t传递给thread1,并编写让main threadwaitthread1finish的代码,而不是thread1waitthread2finish: void *function_thread1(void *ptr){ pthread_t thread2; thread2 = (pthread_t *)ptr; printf("the end of the thread1\n");
main thread
waitthread1
finish的代码,而不是thread1
waitthread2
finish:
void *function_thread1(void *ptr){
pthread_t thread2;
thread2 = (pthread_t *)ptr;
printf("the end of the thread1\n");
pthread_join(thread2,NULL);
pthread_exit(0);
}
void *function_thread2(void *ptr){
printf("the end of the thread2\n");
pthread_exit(0);
}
int main(void){
pthread_t thread1,thread2;
pthread_t *ptr2;
ptr2 = &thread2;
pthread_create(&thread1,NULL,function_thread2,(void*) ptr2);
pthread_create(&thread2,NULL,function_thread1,NULL);
printf("This is the end of main thread\n");
pthread_join(thread1,NULL);
exit(0);
}
它是有效的,但我得到了以下我不知道的警告:
thread_join.c:12:10: warning: incompatible pointer to integer conversion
assigning to 'pthread_t' (aka 'unsigned long') from 'pthread_t *'
(aka 'unsigned long *'); dereference with *
thread2 = (pthread_t *)ptr;
^ ~~~~~~~~~~~~~~~~
*
1 warning generated.
有什么想法吗?你应该做:
pthread_t *thread2;
thread2 = ptr;
pthread_join(*thread2, NULL);
工作起来很有魅力!顺便问一下为什么我不能使用
pthread\u join(*ptr,NULL)
directly@yozloy无法取消引用void*
。调用pthread\u create时传递了错误的函数。函数_thread1将被一个空参数调用,您的代码将(希望)segfault。此外,您的代码还包含一个争用条件:在函数_thread1中(atthread2=(pthread\u t*)ptr;
)*ptr将只包含一些有意义的内容,如果对phtread_create的第二次调用在函数_thread1到达这一点之前完成。@Maughanra感谢您指出竞争条件,我应该很快研究这个主题