线程与条件变量和锁

#include <pthread.h>

#include <stdio.h>

pthread_t       pthid1,pthid2,pthid_control;
pthread_cond_t  cond1,cond2;
pthread_mutex_t mutex;


static void * fun1(void *arg){
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond1,&mutex);

    puts("i am in fun1");

    printf("arg's value is  %d\n",*(int *)arg);
    pthread_mutex_unlock(&mutex);
    return NULL;
}

static void * fun2(void *arg){
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond2,&mutex);

    puts("i am in fun2");

    pthread_mutex_unlock(&mutex);
    return NULL;
}

static void * fun_control(void *arg){
    //TODO
    pthread_cond_signal(&cond1);
    pthread_cond_signal(&cond2);
    return NULL;
}



int main(int argc, const char *argv[])
{

    int arg1 = 5;

    if(0 != pthread_mutex_init(&mutex,NULL)){
        perror("mutex init");
        return -1;
    }

    if(0 != pthread_cond_init(&cond1,NULL)){
        perror("cond1 init");
        return -1;
    }
    if(0 != pthread_cond_init(&cond2,NULL)){
        perror("cond2 init");
        return -1;
    }

    if(0 != pthread_create(&pthid1,NULL,fun1,(void *)&arg1)){
        perror("pthid1");
        return -1;
    }
    if(0 != pthread_create(&pthid2,NULL,fun2,NULL)){
        perror("pthid2");
        return -1;
    }

    sleep(1); //delay the thread

    if(0 != pthread_create(&pthid_control,NULL,fun_control,NULL)){
        perror("pthid3");
        return -1;
    }

    pthread_join(pthid1,NULL);
    pthread_join(pthid2,NULL);
    pthread_join(pthid_control,NULL);

    return 0;
}

第一行 必须要有,编译的时候要加上 -lpthread

第5行定义了线程id变量
第6行定义了条件变量
第7行定义了锁变量

第45行初始化锁,函数在pthread.h中声明

第50/54行初始化条件变量

第59/63/70行新建线程

第75/76/77行连接一个终止的线程,进程会在75行阻塞.如果fun1返回,会阻塞在76行.

重点函数解析

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void (*start_routine) (void ), void *arg);

参数1为 线程id
参数2为 线程属性
参数3为 函数指针,函数声明可以为void * fun (void *);
参数4为 传递的参数,被传递到线程中.

pthread_mutex_lock 加锁

pthread_cond_wait 睡眠,解锁,被唤醒后加锁

pthread_mutex_unlock 解锁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值