python 生产者消费者
时间: 2023-11-09 17:03:20 浏览: 98
生产者消费者问题是一个经典的多线程同步问题,其中生产者线程负责生产数据并将其放入缓冲区,而消费者线程则负责从缓冲区中取出数据并进行消费。以下是一个简单的 Python 生产者消费者示例代码:
```python
import threading
import time
# 缓冲区大小
BUFFER_SIZE = 10
# 生产者线程
class ProducerThread(threading.Thread):
def __init__(self, buffer):
threading.Thread.__init__(self)
self.buffer = buffer
def run(self):
for i in range(20):
item = "item %d" % i
self.buffer.put(item)
print("Produced:", item)
time.sleep(0.5)
# 消费者线程
class ConsumerThread(threading.Thread):
def __init__(self, buffer):
threading.Thread.__init__(self)
self.buffer = buffer
def run(self):
while True:
item = self.buffer.get()
print("Consumed:", item)
time.sleep(1)
# 缓冲区
class Buffer:
def __init__(self):
self.items = []
self.lock = threading.Lock()
self.full = threading.Semaphore(0)
self.empty = threading.Semaphore(BUFFER_SIZE)
def put(self, item):
self.empty.acquire()
self.lock.acquire()
self.items.append(item)
self.lock.release()
self.full.release()
def get(self):
self.full.acquire()
self.lock.acquire()
item = self.items.pop(0)
self.lock.release()
self.empty.release()
return item
# 测试代码
if __name__ == "__main__":
buffer = Buffer()
producer_thread = ProducerThread(buffer)
consumer_thread = ConsumerThread(buffer)
producer_thread.start()
consumer_thread.start()
```
阅读全文