请给我多个生产者和消费者的生产者-消费者问题的代码
时间: 2024-02-19 22:58:49 浏览: 31
好的,以下是多个生产者和消费者的生产者-消费者问题的代码示例:
1. 使用Python标准库中的`Queue`实现:
```python
import threading
import queue
import time
class ProducerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
item = produce_item()
self.queue.put(item)
time.sleep(1)
class ConsumerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
item = self.queue.get()
consume_item(item)
self.queue.task_done()
queue = queue.Queue(maxsize=10)
producer_threads = [ProducerThread(queue) for i in range(5)]
consumer_threads = [ConsumerThread(queue) for i in range(5)]
for t in producer_threads + consumer_threads:
t.start()
queue.join()
```
2. 使用`Condition`实现:
```python
import threading
import time
class ProducerThread(threading.Thread):
def __init__(self, buffer, condition):
threading.Thread.__init__(self)
self.buffer = buffer
self.condition = condition
def run(self):
while True:
item = produce_item()
with self.condition:
while len(self.buffer) >= 10:
self.condition.wait()
self.buffer.append(item)
self.condition.notify_all()
time.sleep(1)
class ConsumerThread(threading.Thread):
def __init__(self, buffer, condition):
threading.Thread.__init__(self)
self.buffer = buffer
self.condition = condition
def run(self):
while True:
with self.condition:
while not self.buffer:
self.condition.wait()
item = self.buffer.pop(0)
self.condition.notify_all()
consume_item(item)
buffer = []
condition = threading.Condition()
producer_threads = [ProducerThread(buffer, condition) for i in range(5)]
consumer_threads = [ConsumerThread(buffer, condition) for i in range(5)]
for t in producer_threads + consumer_threads:
t.start()
for t in producer_threads + consumer_threads:
t.join()
```
注意:以上代码仅为示例,具体实现需要根据实际情况进行调整。