生产消费问题

仓库类:包含生产和消费两个方法,并且生产和消费要保证线程同步,还要保证库存空和满,库存空时需要消费先暂停(就绪)等待生产(唤醒)后在消费(在唤醒),库存满时生产先暂停(就绪)等待消费(唤醒)后在生产(唤醒),当库存不满但不空时可以边生产边消费(不需要暂停任何一个)
生产类:传入仓库类,创建生产线程(Runnable)/当然也可以Thread方式
消费类:传入仓库类,创建消费线程(Runnable)

主类:new 仓库类、new 生产类、new 消费类、new 生产线程、new 消费线程、开启生产线程、开启消费线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在计算机科学中,"生产者-消费者"(Producer-Consumer)问题是一个经典的并发编程示例,它涉及到两个线程角色:一个生产者(Producer),负责生成数据;另一个消费者(Consumer),负责处理这些数据。这个模型通常用信号量、条件变量或队列等同步原语来协调它们之间的交互,避免数据竞争和死锁。 在C语言中,你可以使用互斥锁(mutex)、条件变量(condition variable)或队列(如`std::queue`)来解决这个问题。下面是一个简单的C++代码示例: ```cpp #include <pthread.h> #include <queue> // 定义生产者和消费者 struct Data { int value; }; void* producer(void* arg) { std::queue<Data> queue; // 生产数据并添加到队列 for (int i = 0; i < 10; ++i) { Data data = {i}; pthread_mutex_lock(&mutex); if (!queue.full()) { queue.push(data); pthread_cond_signal(&cv); // 唤醒消费者 } pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } void* consumer(void* arg) { Data data; while (true) { pthread_mutex_lock(&mutex); while (queue.empty()) { pthread_cond_wait(&cv, &mutex); // 当队列为空时等待 } data = queue.front(); // 从队列中取出数据 queue.pop(); pthread_mutex_unlock(&mutex); // 处理数据 printf("Consumed: %d\n", data.value); } pthread_exit(NULL); } int main() { pthread_t producer_thread, consumer_thread; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cv, NULL); pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cv); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值