#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

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

相关文章:

  • 2021-06-29
  • 2022-12-23
  • 2021-05-28
  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-20
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案