有这段代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void* PrintHello(void* data){
printf("Hello from new thread\n");
pthread_exit(NULL);
}
int main(int argc, char* argv[]){
int rc;
pthread_t thread_id;
T_DATA data;
Data = init_data();
rc = pthread_create(&thread_id, NULL, PrintHello, (void*)data);
if(rc){
printf("\n ERROR: return code from pthread_create is %d \n", rc);
exit(1);
}
sleep(100);
printf("\n Created new thread (%d) ... \n", thread_id);
pthread_join(thread_id);
}
当 main
创建新线程然后执行 sleep(100)
,新线程可能达到pthread_exit
之前 main
达到pthread_join
.无论如何,新线程等待并且他的资源直到main
才被释放。执行 pthread_join
所以如果我执行 ps
命令我将在接下来的 100 秒内看到新线程,对吗?如果我使用 pthread_detach
,我会得到相同的行为相反 pthread_join
?我想知道当新线程执行 pthread_exit
时会发生什么主表演前pthread_detach
在线程上。
最佳答案
当然,线程在终止之前不能被清理。但在加入或分离之前也无法清除它。一个没有被分离而终止的线程将保留足够的信息以允许另一个线程加入它。
关于c - 在调用 pthread_join 之前到达 pthread_exit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230972/