我所知道的是 detach() 使 main 函数不等待所有线程完成。
#include <unistd.h>
#include <iostream>
#include <pthread.h>
using namespace std;
void *threadFunction(void *arg){
cout<<"hello world = "<< *((int*)arg) <<endl;
return 0;
}
int main() {
int a = 10;
pthread_t tid;
pthread_create(&tid,NULL,threadFunction,(void*)&a);
pthread_detach(tid);
cout<<"hello world"<<endl;
return 0;
}
这是代码示例,但为什么 threadFunction 没有被执行,因为之前当我运行代码时, threadFunction 被调用,但在我再次运行代码后, threadFunction 没有被调用。为什么会发生这样的事?.
有时我从线程函数中得到意想不到的值,在我得到随机值之后得到 10 之前
分离线程并不能保证它有时间完成运行。您在程序中存在竞争条件。一旦
main
返回,整个程序就退出。
尝试在主程序末尾添加睡眠并查看差异。