Linux线程终止

本文详细介绍了在多线程环境中,如何通过不同的方法使单个线程退出而不影响其他线程或整个进程的运行,包括从启动例程返回、被其他线程取消以及调用pthread_exit函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      进程中的任一线程调用了exit,_Exit或者_exit,那么整个进程都会终止

      单个线程在不终止整个进程的情况下停止它的控制流,有三种方式:

(1)线程只是从启动例程中返回,返回值是线程的退出码。

(2)线程可以被同一进程中的其他线程取消。

(3)线程调用pthread_exit。

1、单个线程调用exit,_Exit或者_exit

void* task1(void* arg)
{
    while (1) {sleep(1);printf("thread1 running...\n");}
    return NULL;
}

void* task2(void *arg)
{
  while (1) {sleep(1);printf("thread2 running...\n");}

  return NULL; } void* task3(void *arg) { int i = 0; while (i++ < 5) {sleep(1);printf("thread3 running...\n");} exit(1); //_Exit(1); //_exit(1); return NULL; } int main(int argc, char *argv[]) { pthread_t thrd1, thrd2, thrd3; pthread_create(&thrd1, NULL, (void*)task1, NULL); pthread_create(&thrd2, NULL, (void*)task2, NULL); pthread_create(&thrd3, NULL, (void*)task3, NULL); pthread_join(thrd1, NULL); pthread_join(thrd2, NULL); pthread_join(thrd3, NULL); printf("Main thread exit...\n"); return 0; }

程序输出:

[root@robot ~]# vim thread_exit.c
[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit
[root@robot ~]# ./thread_exit
thread2 running...
thread3 running...
thread1 running...
thread2 running...
thread3 running...
thread1 running...
thread2 running...
thread3 running...
thread1 running...
thread2 running...
thread3 running...
thread1 running...
thread2 running...
thread3 running...
[root@robot ~]#

这里可以看到调用exit、_Exit、_exit会使整个进程退出。
2、单个线程调用pthread_exit

void pthread_exit(void* rval_ptr);

rval_ptr是一个无类型指针,可以通过调用pthread_join函数访问到这个指针。

void* task1(void* arg)
{
    int i = 0;
    while (i++ < 5) { sleep(1); printf("thread1 running...\n"); }
    pthread_exit((void*)23);

    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t thrd1, thrd2, thrd3;
    void* tret;

    pthread_create(&thrd1, NULL, (void*)task1, NULL);
    pthread_join(thrd1, &tret);

    printf("thread1 return code:%d\n", (int)tret);
    printf("Main thread exit...\n");
    return 0;
}

程序输出:

[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit
[root@robot ~]# ./thread_exit
thread1 running...
thread1 running...
thread1 running...
thread1 running...
thread1 running...
thread1 return code:23
Main thread exit...
[root@robot ~]#

 

转载于:https://www.cnblogs.com/Robotke1/archive/2013/05/01/3053441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值