ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

线程终止

2019-07-29 11:02:32  阅读:165  来源: 互联网

标签:run int fun exit pthread 终止 线程


进程终止时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 \n",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\n",strerror(errno));
    } 
    else    
    {
        printf("thread_create success\n");
    }
        
    void *p = NULL;
    pthread_join(t1,&p);
    printf("thread exit : code = %d\n",*(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的使用时一样的,都会被等待它结束的主线程获取到。

标签:run,int,fun,exit,pthread,终止,线程
来源: https://www.cnblogs.com/wanghao-boke/p/11262731.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有