为什么pthread_join不阻塞并等待线程完成? #包括 #包括 空心*螺纹(空心*v){ printf(“线程现在开始\n”); //pthread_exit(NULL); } int main(){ 国际贸易总协定1; int-retValue=0; pthread_create(&tid1,NULL,thread,NULL); retValue=pthread_join(tid1,NULL); printf(“线程ID:%d,返回值:%d\n”,tid1,retValue); retValue=pthread_join(tid1,NULL); printf(“线程ID:%d,返回值:%d\n”,tid1,retValue); 返回0; }
有时输出为:为什么pthread_join不阻塞并等待线程完成? #包括 #包括 空心*螺纹(空心*v){ printf(“线程现在开始\n”); //pthread_exit(NULL); } int main(){ 国际贸易总协定1; int-retValue=0; pthread_create(&tid1,NULL,thread,NULL); retValue=pthread_join(tid1,NULL); printf(“线程ID:%d,返回值:%d\n”,tid1,retValue); retValue=pthread_join(tid1,NULL); printf(“线程ID:%d,返回值:%d\n”,tid1,retValue); 返回0; },c,multithreading,operating-system,pthreads,C,Multithreading,Operating System,Pthreads,有时输出为: 线程ID:1877241856,返回值:3 线程ID:1877241856,返回值:3 线程现在开始 进程已完成,退出代码为0 问题是: 根据定义,pthread\u join应该阻塞,等待thread完成执行,然后执行它后面的代码。但是为什么在我的代码中,thread在两个pthread\u joinfinish之后运行 根据定义,pthread_join返回0表示成功加入,但是为什么我的代码的retValue总是3,无论thread是在pthread_join函数之前还是之
线程ID:1877241856,返回值:3
线程ID:1877241856,返回值:3
线程现在开始
进程已完成,退出代码为0
问题是:
pthread\u join
应该阻塞,等待thread
完成执行,然后执行它后面的代码。但是为什么在我的代码中,thread
在两个pthread\u join
finish之后运行
pthread_join
返回0表示成功加入,但是为什么我的代码的retValue
总是3,无论thread
是在pthread_join
函数之前还是之后运行
此代码中有许多错误:
pthread\u create()
的第一个参数应该是pthread\u t
,而不是int
。它们很可能大小不同,或者可以互换,因此tid1
可能不是有效的pthread id
return
语句
pthread\u join()
。被视为返回值的实际上是pthread\u join()
调用本身的结果。这是一个错误。也许与上面的#1有关
除了TrentP发现的那些缺陷之外,最严重的缺陷是 与先前已连接的线程连接会导致未定义的行为 i、 e.在同一线程上调用
pthread\u join
两次
retValue = pthread_join(tid1, NULL);
retValue = pthread_join(tid1, NULL);
如果您将
tid1
更改为pthread\u t
的话,那么说它有效是完全错误的。未定义的行为意味着当第二次调用pthread\u join
时可能发生任何事情-pthread\u join
可能返回错误,pthread\u join
可能返回成功、崩溃、挂起、修改内存的其他部分,它会导致新线程启动…来自pthread\u join
的返回值告诉您什么?来自编译器的编译器诊断消息在哪里?因为它是不正确的,所以在没有诊断的情况下它不会编译。编译器说“Format指定类型‘unsigned long’,但参数的类型为‘int’”。这是有帮助的,但我不知道我应该阅读诊断信息。谢谢@AnttiHaapala@NameNull因此,下次使用-Werror
编译时,它们将变成错误。也许还有墙。。。但我指的是没有pthread\u t
的原始程序,它会说指向pthread\u create
的指针类型不兼容。将tid1
设置为typepthread\u t
后,程序现在有了预期的行为。第二个retValue
语句是一个实验。我只是想知道当我加入一个已经加入的线程时会发生什么。现在第二个retValue
是3,这是一个错误,正如预期的那样。@NameNull确定,所以您没有阅读我写的内容。这是预料不到的。因为行为是未定义的,所以你不能期望任何东西。您不能再叫它两次。@namefull请看