生产者消费者问题代码实现
时间: 2023-09-17 11:08:38 浏览: 38
生产者消费者问题是一个经典的多线程同步问题,以下是一个简单的代码实现:
```python
import threading
import time
import random
BUFFER_SIZE = 10
buffer = []
lock = threading.Lock()
not_full = threading.Condition(lock)
not_empty = threading.Condition(lock)
class Producer(threading.Thread):
def run(self):
global buffer
while True:
not_full.acquire()
if len(buffer) == BUFFER_SIZE:
print("Buffer is full, producer is waiting")
not_full.wait()
item = random.randint(1, 10)
buffer.append(item)
print("Producer produced", item)
not_empty.notify()
not_full.release()
time.sleep(random.random())
class Consumer(threading.Thread):
def run(self):
global buffer
while True:
not_empty.acquire()
if not buffer:
print("Buffer is empty, consumer is waiting")
not_empty.wait()
item = buffer.pop(0)
print("Consumer consumed", item)
not_full.notify()
not_empty.release()
time.sleep(random.random())
if __name__ == '__main__':
producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()
producer.join()
consumer.join()
```
在这个实现中,生产者和消费者都是继承自 `threading.Thread` 的子类,它们分别不断地向缓冲区中添加和取出数据。同时,我们使用了 `threading.Condition` 来实现缓冲区是否满和是否空的条件判断,从而避免了死锁的问题。