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