Linux系统编程 线程回收 (pthread_join函数)

pthread_join定义,回收线程并接收返回值
在这里插入图片描述

单线程回收

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<pthread.h>
#include<string.h>
typedef struct{
    int val;
    char s[64];
}exit_t;
void* thrd_func(void* arg)
{
    exit_t* retval=(exit_t*)malloc(sizeof(exit_t));
    retval->val=100;
    strcpy(retval->s,"my pthread!");
    pthread_exit((void*)retval);//注意参数格式
}
int main()
{
    pthread_t tid;
    int ret;
    exit_t* result;
    printf("in main1:  thread  ID=%lu, pid=%u\n",pthread_self(),getpid());//主控线程
    ret=pthread_create(&tid,NULL,thrd_func,NULL);//创建新进程
    /*1.tid传出参数
    2.设置线程属性
    3.执行函数,返回void*
    4.函数的传入参数void*
    */
    if(ret!=0)
    {
        printf("pthread_create error\n");
        exit(1);
    }
    pthread_join(tid,(void**)&result);
    //1.传入参数:线程ID
    //2.传出参数,进程结束返回值,可以是多种数据形式
    printf("val=%d-----s=%s\n",result->val,result->s);
    free(result); 
    pthread_exit((void*)1);

}

多线程回收

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<pthread.h>
#include<string.h>
int val=100;
void* thrd_func(void* arg)
{
    int i;
    i=(int)arg;
    sleep(i);
    if(i==1)
    {
        val=333;
        printf("val=%d\n",val);
        return (void*)val;
    }
    else if(i==3)
    {
        val=777;
        printf("I'm %dth pthread, id = %lu, val=%d\n",i+1,pthread_self(),val);
        pthread_exit((void*)val);
    }
    else
    {
        printf("I'm %dth pthread, id = %lu, val=%d\n",i+1,pthread_self(),val);
    }
    return NULL;
}
int main()
{
    pthread_t tid[5];
    int ret;
    int* ans[5];
    int i;
    printf("in main1:  thread  ID=%lu, pid=%u\n",pthread_self(),getpid());//主控线程
    for(i=0;i<5;i++)
    {
        ret=pthread_create(&tid[i],NULL,thrd_func,(void*)i);//创建新线程
        /*1.tid传出参数
          2.设置线程属性
          3.执行函数,返回void*
          4.函数的传入参数void*
          */
        if(ret!=0)
        {
            printf("pthread_create error\n");
            exit(1);
        }
    }
    for(i=0;i<5;i++)
    {
        pthread_join(tid[i],(void**)&ans[i]);
        printf("------%d  return %d\n",i+1,(int)ans[i]);
    }
    pthread_exit((void*)1);//退出主控线程

}

结果如下,子线程依次回收
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值