2013-11-27 32 views
0

有了这段代码之前达到:了pthread_exit()调用在pthread_join

#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_joinpthread_exitmain之前。无论如何,新的线程等待,他的资源不会释放,直到main执行pthread_join因此,如果我执行ps命令我会看到新的线程在接下来的100秒内,我对吗?如果我使用pthread_detach而不是pthread_join,我会得到相同的行为?我想知道在主线程执行pthread_detach之前,新线程执行pthread_exit会发生什么情况。

回答

1

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

+0

因此,当我执行'ps'直到主执行'pthread_exit'或'pthread_detach'并且之后不再存在,所以它不会再被命令'ps'显示时,新线程仍然显示? – MABC

+0

'ps'显示进程不是线程。 –

+0

@R ..在Linux上,'ps'也可以显示线程。 'ps -H'。 –