zoukankan      html  css  js  c++  java
  • 线程终止

    进程终止时exit()函数,那么线程终止的是什么呢?

    线程终止的三种情况:

    1. 线程只是从启动函数中返回,返回的是线程的退出码;
    2. 线程可以被同一进程中的其他线程取消;
    3. 线程调用pthread_exit。
    /***
    exit.c
    ***/
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<errno.h>
    #include<pthread.h>
    
    void *func(void *arg)
    {
        int i = 0;
        while(1)
        {
            if(10 == i)
            {
                int *p = (int *)malloc(sizeof(int));
                *p = 11;
                pthread_exit(p);
            }
            printf("fun run %d 
    ",i++);
            sleep(1);
        }
        return NULL;
    }
    
    int main()
    {
        pthread_t t1,t2;
        int err = pthread_create(&t1,NULL,func,NULL);
        if( 0 != err)
        {
            printf("thread_create failed : %s
    ",strerror(errno));
        } 
        else    
        {
            printf("thread_create success
    ");
        }
            
        void *p = NULL;
        pthread_join(t1,&p);
        printf("thread exit : code = %d
    ",*(int *)p);
        return EXIT_SUCCESS;
    }

    运行结果:

    exbot@ubuntu:~/wangqinghe/thread/20190729$ gcc exit.c -o exit -lpthread

    exbot@ubuntu:~/wangqinghe/thread/20190729$ ./exit

    thread_create success

    fun run 0

    fun run 1

    fun run 2

    fun run 3

    fun run 4

    fun run 5

    fun run 6

    fun run 7

    fun run 8

    fun run 9

    thread exit : code = 11

    void pthread_exit(void *arg)

    pthread_exit函数的参数就跟正常线程结束return的使用时一样的,都会被等待它结束的主线程获取到。

  • 相关阅读:
    学习进度笔记
    学习进度笔记
    学习进度笔记
    学习进度笔记
    博雅数据机器学习10
    学习进度笔记
    HDFS上文件权限操作
    HBase的安装与使用
    hadoop完全分布式安装教程
    python安装easygui
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11262731.html
Copyright © 2011-2022 走看看