ARTS-S C语言主线程获取子线程返回值

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

typedef struct {
    int stu_num;
    char* stu_name;
}Student;

void *thr_fn1(void *arg) {
    Student* student = (Student*)malloc(sizeof(Student));
    student->stu_num = 1;
    student->stu_name = "name1";
    return((void *)student);
}

void *thr_fn2(void *arg) {printf("thread 2 exiting\n");
    Student* student = (Student*)malloc(sizeof(Student));
    student->stu_num = 2;
    student->stu_name = "name2";
    return((void *)student);
}

int main(void) {
    int         err;
    pthread_t   tid1, tid2;
    void        *tret;
    err = pthread_create(&tid1, NULL, thr_fn1, NULL);
    if (err != 0)
        printf("can’t create thread 1:%d", err);
    err = pthread_create(&tid2, NULL, thr_fn2, NULL);
    if (err != 0)
        printf("can’t create thread 2:%d", err);
    err = pthread_join(tid1, &tret);
    if (err != 0)
        printf("can’t join with thread 1:%d", err);

    printf("thread 1 number=%d,name=%s\n", ((Student*)tret)->stu_num, ((Student*)tret)->stu_name);
    err = pthread_join(tid2, &tret);
    if (err != 0)
        printf("can’t join with thread 2:%d", err);
    printf("thread 2 number=%d,name=%s\n", ((Student*)tret)->stu_num, ((Student*)tret)->stu_name);
    exit(0);
}
// gcc -Wall main1.c -lpthread -o demo

可用于主线程等子线程完成.

posted on 2019-07-06 21:42  荷楠仁  阅读(719)  评论(0编辑  收藏  举报

导航