线程终止

进程终止时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的使用时一样的,都会被等待它结束的主线程获取到。

posted @   王清河  阅读(173)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2018-07-29 1002 A+B for Polynomials (25)
2018-07-29 1001 A+B Format (20)
点击右上角即可分享
微信分享提示