pthread_exit-----在linux主线程中的用途

来源:互联网 发布:淘宝平板版下载 编辑:程序博客网 时间:2024/06/07 17:28

大家都知道在一个线程中调用pthread_exit表示退出一个线程,并且pthread_exit的参数作为返回值提供给pthread_join函数获取。
那么如果在main函数创建了若干个线程后,在main函数最后调用pthread_exit会怎么样呢?已经创建的线程会不会随着main线程的退出而退出呢?
如果在main函数中调用的是exit,那么答案是所有线程随着main线程退出而退出。
但是对于pthread_exit而言,又是另外一个故事了。
在main函数中调用pthread_exit, 只有main线程自己退出,已经创建的线程并不会随之一起退出。

#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <string.h>#include <errno.h>#include <sys/types.h>#include <unistd.h>pthread_t ntid;void printtids(const char *s) {    pid_t pid;    pthread_t tid;    pid = getpid();    tid = pthread_self();    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);}void *thread_func(void *arg){    sleep(1); /*故意在子线程中sleep 1,保证子线程在main线程以后退出*/    printtids("new thread: ");    return NULL; }int main(int argc, char *argv[]){    int rc;     rc = pthread_create(&ntid, NULL, thread_func, NULL);    if (rc != 0) {        printf("pthread_create error: %s\n", strerror(errno));    }       printtids("main thread: ");    pthread_exit(NULL);   /*main线程退出,后面的话不会打印了*/                                                                                                                                                        printf("main process is exited...\n");    return 0;}

编译运行:
发现进程ID是一样的,线程ID不一致,并且在”main thread…”, 输出以后停顿了一下(sleep 1)后输出”new thread…”.
而且没有输出“main process is exited…”
说明pthread_exit 只退出了main线程,其它线程并没有随之退出

gwwu@hz-dev2.aerohive.com:~/test/thread>gcc -g thread1.c -o thread1 -lpthread -Wallgwwu@hz-dev2.aerohive.com:~/test/thread>./thread1 main thread:  pid 19066 tid 291600128 (0x11617700)new thread:  pid 19066 tid 291591936 (0x11615700)gwwu@hz-dev2.aerohive.com:~/test/thread>