我对一些正在测试以开始理解 posix 线程的代码有疑问。
我有这个基本代码:
#include <iostream>
#include <string>
#include <sstream>
#include <pthread.h>
using namespace std;
void *printInfo(void *thid){
long tid;
tid =(long)thid;
printf("Hello from thread %ld.\n",tid);
pthread_exit(NULL);
}
int main (int argc, char const *argv[])
{
int num =8;
pthread_t threadlist[num];
int rc;
long t;
for(t=0;t<num;t++){
printf("Starting thread %ld\n",t);
rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t);
if(rc)
{
printf("Error creating thread");
exit(-1);
}
}
pthread_exit(NULL);
return 0;
}
非常简单的代码,启动线程并从中打印,这一切都很神奇,只是我不明白最后一个 pthread_exit(NULL)
在 return 0;
之前在主要方法的末尾。
看来主线程不应该是pthread,也不应该是pthread!如果我不放置它,代码将无法运行:代码编译并执行,但我只得到“起始线程”打印消息,而不是“hello from ...”消息。
所以基本上我想知道为什么需要这样做。
此外,如果我注释掉 include <psthread.h>
,代码将正确编译和执行。 .
最佳答案
如果您不在 main 函数中使用 pthread_exit,那么所有创建的线程都会在 main 完成时终止,即在您的情况下,它们还没有打印任何内容。
通过在 main 函数中调用 pthread_exit 使 main 等待所有线程完成。
来自 pthread_exit 手册页:
The process will exit with an exit status of 0 after the last thread has been terminated. The behavior is as if the implementation called exit() with a zero argument at thread termination time.
这是指从主进程线程调用 pthread_exit()。
关于c++ - 为什么我需要从主线程使用 `pthread_exit()`,而它不是由 `pthread_create` 创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313528/