线程的回收

*void pthread_exit(void retval);:单个线程推出

对比:exit() :进程退出
区别以下三者:
(1) exit():整个进程退出;
(2)pthread_exit():当前线程退出;
(3) return : 返回调用者那里去;

**int pthread_join(pthread_t thread, void retval): 阻塞等待线程退出

对比: wait阻塞等待子进程退出

单个线程的退出

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
typedef struct{
        char c;
        int a;
        char * ch[64];
}exit_t;

void *pthread_fun(void *arg)
{ 
        exit_t * retval = (exit_t *)arg;

        retval->c='m';
        retval->a=10;
        strcpy(retval->ch,"hello world\n");
        pthread_exit((void *)10);

}
int main()
{
        pthread_t tid;
        int ret;
        exit_t * retval;

        ret = pthread_create(&tid,NULL,pthread_fun,(void *)retval);
        if(ret != 0)
        {
                printf("ptthread_cretea error");
                exit(1);
        }
        sleep(1);
        printf("c=%c   a = %d   ch=%s\n",retval->c,retval->a,retval->ch);

        int *pv;
        pthread_join(tid,(void **)&pv );
        printf("pv=%d\n",(int)pv);
        return 0;
}

回收多个线程

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

void *pthread_fun(void *arg)
{
        int i= (int) arg;
        sleep(i);
        printf("%dth tid=%d\n",i+1,pthread_self());
        pthread_exit((void *)i);
}
int main()
{
        pthread_t tid[5];
        int ret,i;

        for(i = 0; i<5; ++i)
        {
                ret = pthread_create(&tid[i],NULL,pthread_fun,(void *)i);
                if(ret != 0)
                {
                        printf("ptthread_cretea error");
                        exit(1);
                }
        }


        for(i = 0; i<5; ++i)
        {
                int * retval;
                pthread_join(tid[i],(void **)&retval);
                printf("%dth finish\n ",(int)retval);
        }
        sleep(i);

        return 0;
}
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YanWenCheng_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值