• Linux线程终止


          进程中的任一线程调用了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 ~]#
  • 相关阅读:
    ① ts基础
    ⑦ 原型和原型链 作用域链
    ④ 小程序使用分包
    功能⑦ 小程序整合高德地图定位
    effective OC2.0 52阅读笔记(三 接口与API设计)
    effective OC2.0 52阅读笔记(二 对象、消息、运行期)
    effective OC2.0 52阅读笔记(一 熟悉Objective-C)
    perl的Getopt::Long和pod::usage ?
    安装你自己的perl modules
    Perl 之 use(), require(), do(), %INC and @INC
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3053441.html
Copyright © 2020-2023  润新知