进程同步生产者消费者问题代码
时间: 2023-12-20 18:29:30 浏览: 50
以下是使用Python中的queue模块解决生产者-消费者问题的代码:
```python
import threading
import queue
import time
# 生产者线程
class ProducerThread(threading.Thread):
def __init__(self, queue, name):
threading.Thread.__init__(self)
self.queue = queue
self.name = name
def run(self):
while True:
if self.queue.qsize() < 10:
self.queue.put("product")
print("Producer {} produces a product. Now the queue size is {}.".format(self.name, self.queue.qsize()))
time.sleep(1)
# 消费者线程
class ConsumerThread(threading.Thread):
def __init__(self, queue, name):
threading.Thread.__init__(self)
self.queue = queue
self.name = name
def run(self):
while True:
if self.queue.qsize() > 0:
self.queue.get()
print("Consumer {} consumes a product. Now the queue size is {}.".format(self.name, self.queue.qsize()))
time.sleep(2)
# 创建一个队列
q = queue.Queue()
# 创建两个生产者线程和三个消费者线程
producer1 = ProducerThread(q, "P1")
producer2 = ProducerThread(q, "P2")
consumer1 = ConsumerThread(q, "C1")
consumer2 = ConsumerThread(q, "C2")
consumer3 = ConsumerThread(q, "C3")
# 启动线程
producer1.start()
producer2.start()
consumer1.start()
consumer2.start()
consumer3.start()
```