条件变量实现生产消费问题
2014-09-18 13:27
260 查看
条件变量:
等待线程:
pthread_mutex(&mutex);//对条件变量加锁
while(条件)//阻塞的条件
{
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex(&mutex);
通知线程:
pthread_mutex(&mutex);//对条件变量加锁
if(条件)//条件发生
{
pthread_cond_signal(&cond);
}
pthread_mutex(&mutex);
等待线程:
pthread_mutex(&mutex);//对条件变量加锁
while(条件)//阻塞的条件
{
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex(&mutex);
通知线程:
pthread_mutex(&mutex);//对条件变量加锁
if(条件)//条件发生
{
pthread_cond_signal(&cond);
}
pthread_mutex(&mutex);
<span style="font-size:18px;">#include "stdio.h" #include <stdlib.h> #include <pthread.h> #define N_CONSUMER 3 //消费者数量 #define N_PRODUCER 2 //生产者数量 #define C_SLEEP 1 //控制 consumer 消费的节奏 #define P_SLEEP 1 //控制 producer 生产的节奏 pthread_mutex_t mutex; pthread_cond_t condp,condc; int cnt=0;//缓冲区当前的产品数 int MAX=4;//缓冲区大小 void * produce(void * arg) { while(1) { pthread_mutex_lock(&mutex); while(cnt==MAX) { printf("produce waiting:\n"); pthread_cond_wait(&condp,&mutex); } printf("produce %u now: ",(unsigned int)pthread_self()); cnt++; printf("the number is:%d\n",cnt); sleep(2); pthread_mutex_unlock(&mutex); pthread_cond_signal(&condc); } return 0; } void * consume(void * arg) { while(1) { pthread_mutex_lock(&mutex); while(cnt==0) { printf("comsume waiting:\n"); pthread_cond_wait(&condc,&mutex); } printf("comsume %u now: ",(unsigned int)pthread_self()); cnt--; printf("the number is:%d\n",cnt); pthread_mutex_unlock(&mutex); sleep(1); pthread_cond_signal(&condp); } return 0; } int main() { pthread_t ptid[N_PRODUCER]; pthread_t ctid[N_CONSUMER]; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&condp,NULL); pthread_cond_init(&condc,NULL); int i=0; for(i=0;i<N_PRODUCER;i++) pthread_create(&ptid[i],NULL,produce,NULL); for(i=0;i<N_CONSUMER;i++) pthread_create(&ctid[i],NULL,consume,NULL); sleep(1000); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condp); pthread_cond_destroy(&condc); return 0; }</span>
相关文章推荐
- AutoResetEvent来模拟实现生产消费问题
- 【代码练习6】利用多线程生产消费问题实现熊吃蜂蜜问题
- linux 下 条件变量实现生产者消费者问题
- 经典的生产与消费线程同步问题
- 并发编程(二):分析Boost对 互斥量和条件变量的封装及实现生产者消费者问题
- 多线程之生产消费问题
- 单生产单消费多生产多消费问题的解决及使用机制
- Linux下的简单生产、消费模型的实现(上)
- java中多线程模拟(多生产,多消费,Lock实现同步锁,替代synchronized同步代码块)
- 并发编程(一): POSIX 使用互斥量和条件变量实现生产者/消费者问题
- 并发编程(一): POSIX 使用互斥量和条件变量实现生产者/消费者问题
- 初次尝试ActiveMQ,实现简单的消息生产和消息消费
- 用java实现生产和消费
- Java模拟生产消费问题
- 生产/消费模型的java实现
- 并发编程(二):分析Boost对 互斥量和条件变量的封装及实现生产者消费者问题
- 线程 --生产和消费问题
- 生产/消费模型的java实现
- NSCondition的用法,NSCondication实现线程同步,生产者消费问题实现(转载)
- Java中多线程的多生产多消费问题的解决方案