生产者消费者python
时间: 2023-11-20 11:57:49 浏览: 91
生产者消费者模型是一种常见的并发编程模型,其中生产者负责生成数据,消费者负责处理数据,而缓冲区则用于存储数据。以下是一个简单的Python实现:
```python
import threading
import time
# 缓冲区大小
BUFFER_SIZE = 10
# 生产者类
class Producer(threading.Thread):
def __init__(self, name, buffer):
threading.Thread.__init__(self)
self.name = name
self.buffer = buffer
def run(self):
for i in range(10):
# 生产数据
data = self.name + str(i)
# 将数据放入缓冲区
self.buffer.put(data)
print("Producer %s produced %s" % (self.name, data))
time.sleep(1)
# 消费者类
class Consumer(threading.Thread):
def __init__(self, name, buffer):
threading.Thread.__init__(self)
self.name = name
self.buffer = buffer
def run(self):
while True:
# 从缓冲区取出数据
data = self.buffer.get()
print("Consumer %s consumed %s" % (self.name, data))
time.sleep(2)
# 缓冲区类
class Buffer():
def __init__(self):
self.buffer = []
self.lock = threading.Lock()
self.full = threading.Semaphore(0)
self.empty = threading.Semaphore(BUFFER_SIZE)
def put(self, data):
self.empty.acquire()
self.lock.acquire()
self.buffer.append(data)
self.lock.release()
self.full.release()
def get(self):
self.full.acquire()
self.lock.acquire()
data = self.buffer.pop(0)
self.lock.release()
self.empty.release()
return data
# 创建缓冲区
buffer = Buffer()
# 创建生产者和消费者线程
producer1 = Producer("A", buffer)
producer2 = Producer("B", buffer)
consumer1 = Consumer("X", buffer)
consumer2 = Consumer("Y", buffer)
# 启动线程
producer1.start()
producer2.start()
consumer1.start()
consumer2.start()
```
上述代码中,生产者和消费者都是继承自`threading.Thread`的类,通过重写`run`方法实现线程的执行逻辑。缓冲区使用了一个列表来存储数据,并使用了`threading.Lock`来保证线程安全。同时,使用了两个信号量`full`和`empty`来控制缓冲区的状态,其中`full`表示缓冲区中已有的数据数量,`empty`表示缓冲区中还可以存放的数据数量。
阅读全文