生产者消费者算法代码实现
时间: 2024-06-17 12:02:43 浏览: 15
生产者消费者算法是一种用于解决多线间数据共享和同步的经典问题。下面是一个简单的生产者消费者算法的代码实现:
```python
import threading
import time
import random
# 共享的缓冲区
buffer = []
buffer_size = 5
# 互斥锁和条件变量
mutex = threading.Lock()
not_full = threading.Condition(mutex)
not_empty = threading.Condition(mutex)
# 生产者线程
class Producer(threading.Thread):
def run(self):
global buffer
while True:
mutex.acquire()
while len(buffer) == buffer_size:
print("缓冲区已满,生产者等待...")
not_full.wait()
item = random.randint(1, 10)
buffer.append(item)
print("生产者生产了一个物品:", item)
not_empty.notify()
mutex.release()
time.sleep(random.random())
# 消费者线程
class Consumer(threading.Thread):
def run(self):
global buffer
while True:
mutex.acquire()
while len(buffer) == 0:
print("缓冲区为空,消费者等待...")
not_empty.wait()
item = buffer.pop(0)
print("消费者消费了一个物品:", item)
not_full.notify()
mutex.release()
time.sleep(random.random())
# 创建生产者和消费者线程并启动
producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()
```
上述代码中,生产者线程不断地向缓冲区中添加物品,如果缓冲区已满,则生产者线程等待。消费者线程不断地从缓冲区中取出物品,如果缓冲区为空,则消费者线程等待。通过互斥锁和条件变量的配合,实现了生产者和消费者之间的同步和互斥。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)