Linux高级编程(线程操作)

问题:创建2条线程对一个变量money进行处理,线程A对money进行消费, 每1s消费50, 线程B对money进行充值, 如果money > 200; 线程B进入睡眠, 线程A在消费过程中发现money <= 200; 就唤醒线程B, 线程B对money进行充值,一次充值300。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */

pthread_cond_t cond;        //条件变量
pthread_mutex_t mutex;	    //互斥锁
//线程A对money进行消费, 每1s消费50
void *funA(void *arg)
{
 while(1)
 {
  pthread_mutex_lock(&mutex);
  money -= 50;
  printf("money:%d\n", money);
  sleep(1);
  if(money <200)
  {
   printf("money less 200!call B\n");
   pthread_cond_signal(&cond);		//线程A在消费过程中发现money <= 200; 就唤醒线程B,
  }
  pthread_mutex_unlock(&mutex);
  sleep(1);
 }
}
//如果money > 200;  线程B进入睡眠,线程B对money进行充值,一次充值300
void *funB(void *arg)
{
 while(1)
 {
  pthread_mutex_lock(&mutex);
  if(money > 200)
  {
   printf("funB is sleep!\n");
   pthread_cond_wait(&cond, &mutex);
  }
  money += 300;
  printf("line B:money:%d\n", money);
  pthread_mutex_unlock(&mutex);
  }
}
int main()
{
  money =500;
 //1.初始化条件变量和互斥锁
 pthread_cond_init(&cond, NULL);
 pthread_mutex_init(&mutex, NULL);
 //2.创建两条子线程
 pthread_t tid1,tid2;
 pthread_create(&tid1, NULL, funA, NULL);
 pthread_create(&tid2, NULL, funB, NULL);
 //3.等待回收子线程资源
 pthread_join(tid1, NULL);
 pthread_join(tid2, NULL);
 //4.销毁条件变量和互斥锁
 pthread_cond_destroy(&cond);
 pthread_mutex_destroy(&mutex);
 return 0;
}

在线程中,条件变量的作用是让线程进入睡眠,只有在满足某种条件的情况下,才唤醒线程,让线程去执行任务。
 条件变量一般需要跟互斥锁一起使用。
 在使用条件变量时,需要对变量进行保护(一条线程在使用这个变量时,其他线程都不能使用这个变量   互斥锁)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序小鹿

博主不差钱,点个赞就行哈哈

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值