循环创建多个子线程并使用pthread_join函数回收

Demo

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>

struct thrd
{
    int var;
    char str[256];
};
void sys_err(const char *str)
{
    perror(str);
    exit(1);
}
//定义回调函数
void *tfn(void *arg)
{
    int i = (int)arg;
    struct thrd *tval;
    tval = malloc(sizeof(tval));
    //tval->var = 100;
    tval->var = i;
    strcpy(tval->str, "hello thread");
    printf("---I'm child %d, pid = %d, tid = %lu\n", i+1, getpid(), pthread_self());
    //函数返回时子线程结束
    sleep(i);
    return (void *)tval;
}

int main(int argc, char *argv[])
{
    pthread_t tid[5];
    struct thrd *retval[5];
    int i, j, ret;
    for(i = 0; i < 5; i++)
    {
        //int ret = pthread_create(&tid, NULL, tfn, NULL);
        ret = pthread_create(&tid[i], NULL, tfn, (void *)i);
        if(ret != 0) sys_err("pthread_create error");
    }
    for(j = 0; j < 5; j++)
    {
        ret = pthread_join(tid[j], (void **)&retval[j]);
        if(ret != 0) sys_err("pthread_join error");
        printf("child thread %d exit with var = %d, str = %s\n", j+1, retval[j]->var, retval[j]->str);
        
    }
    if(i == 5)
    {
        printf("I'm main, pid = %d, tid = %lu\n", getpid(), pthread_self());
    }
    //pthread_join(tid, (void **)&retval);
    return 0;
}

执行结果

---I'm child 1, pid = 4278, tid = 140318439139072
---I'm child 2, pid = 4278, tid = 140318430746368
---I'm child 4, pid = 4278, tid = 140318422353664
---I'm child 3, pid = 4278, tid = 140318288135936
---I'm child 5, pid = 4278, tid = 140318413960960
child thread 1 exit with var = 0, str = hello thread
child thread 2 exit with var = 1, str = hello thread
child thread 3 exit with var = 2, str = hello thread
child thread 4 exit with var = 3, str = hello thread
child thread 5 exit with var = 4, str = hello thread
I'm main, pid = 4278, tid = 140318447634240
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值