0

有这段代码:

#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_detachpthread_join?我想知道当新线程在线程上执行pthread_exit之前的 main 执行时会发生什么pthread_detach

4

1 回答 1

1

当然,线程在终止之前不能被清理。但它也不能被清理,直到它被连接或分离。一个未分离就终止的线程将保留足够的信息以允许另一个线程加入它。

于 2013-11-27T00:55:09.467 回答