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

大家都知道在一个线程中调用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 -Wall gwwu@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>

 

转载自:https://blog.csdn.net/jackywgw/article/details/73807171

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值