Skip to main content
 首页 » 编程设计

c之在调用 pthread_join 之前到达 pthread_exit()

2026年04月21日46txw1958

有这段代码:

#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在线程上。

请您参考如下方法:

当然,线程在终止之前不能被清理。但在加入或分离之前也无法清除它。一个没有被分离而终止的线程将保留足够的信息以允许另一个线程加入它。