zoukankan      html  css  js  c++  java
  • 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 ~]#
  • 相关阅读:
    关于多态
    关于lock锁
    wait()和notify()
    多线程之间的通讯
    多线程的异步请求模式
    合理配置线程池
    自定义线程池
    Curl的毫秒超时的一个”Bug”
    Nginx正确记录post日志的方法
    NGINX的奇淫技巧 —— 5. NGINX实现金盾防火墙的功能(防CC)
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3053441.html
Copyright © 2011-2022 走看看