基于c语言的多线程示例

dual_pthread

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

typedef struct {
    int id;
    char s;
}stu;

pthread_t th_1;
pthread_t th_2;
pthread_t th_3;
pthread_t th_4;

stu *first, *second;

static void *thread_func(void *context)
{
    stu* ss = (stu *)context;
    printf("this value is %d, name is %c\n", ss->id, ss->s);

}


static int thread_start(void)
{
    if(pthread_create(&th_1, NULL, thread_func, first) != 0){
        printf("######error#####:create thread first failed!\n");
        return -1;
    }

    if(pthread_create(&th_2, NULL, thread_func, second) != 0){
        printf("######error#####:create thread first failed!\n");
        return -1;
    }

    return 0;
}

static void thread_pre(void)
{
    first = (stu *)malloc(sizeof(stu));
    first->id = 0;
    first->s = 'a';
    second = (stu *)malloc(sizeof(stu));
    second->id = 1;
    second->s = 'b';
}

static int pthread_exit_m(void)
{

    if(pthread_join((th_1), NULL) != 0){
        printf("######warning#####:exit thread first failed!\n");
    }

    if(pthread_join((th_2), NULL) != 0){
        printf("######warning#####:exit thread second failed!\n");
    }

    return 0;
}

int main(void)
{
    thread_pre();
    int ret = thread_start();
    pthread_exit_m();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值