线程同步实现生产者消费者
时间: 2023-11-12 21:00:47 浏览: 92
线程实现生产者消费者
生产者消费者问题是一个经典的线程同步问题,下面给出一种实现方式:
```python
import threading
import time
# 缓冲区容量
BUFFER_SIZE = 10
# 生产者线程
class ProducerThread(threading.Thread):
def __init__(self, buffer, mutex, empty, full):
threading.Thread.__init__(self)
self.buffer = buffer
self.mutex = mutex
self.empty = empty
self.full = full
def run(self):
for i in range(20):
# 等待缓冲区非满
self.empty.acquire()
# 获取互斥锁
self.mutex.acquire()
# 生产数据
self.buffer.append(i)
print("Producer produced", i)
# 释放互斥锁
self.mutex.release()
# 发送信号通知缓冲区非空
self.full.release()
# 等待一段时间
time.sleep(0.5)
# 消费者线程
class ConsumerThread(threading.Thread):
def __init__(self, buffer, mutex, empty, full):
threading.Thread.__init__(self)
self.buffer = buffer
self.mutex = mutex
self.empty = empty
self.full = full
def run(self):
for i in range(20):
# 等待缓冲区非空
self.full.acquire()
# 获取互斥锁
self.mutex.acquire()
# 消费数据
item = self.buffer.pop(0)
print("Consumer consumed", item)
# 释放互斥锁
self.mutex.release()
# 发送信号通知缓冲区非满
self.empty.release()
# 等待一段时间
time.sleep(0.5)
if __name__ == "__main__":
# 初始化缓冲区、互斥锁、信号量
buffer = []
mutex = threading.Lock()
empty = threading.Semaphore(BUFFER_SIZE)
full = threading.Semaphore(0)
# 创建生产者、消费者线程
producer = ProducerThread(buffer, mutex, empty, full)
consumer = ConsumerThread(buffer, mutex, empty, full)
# 启动线程
producer.start()
consumer.start()
# 等待线程结束
producer.join()
consumer.join()
```
在上述代码中,缓冲区使用列表实现,互斥锁使用 Lock 对象实现,信号量使用 Semaphore 对象实现,其中 empty 表示缓冲区非满,full 表示缓冲区非空。生产者线程在生产数据前需要等待缓冲区非满,获取互斥锁后生产数据,释放互斥锁后发送信号通知缓冲区非空。消费者线程在消费数据前需要等待缓冲区非空,获取互斥锁后消费数据,释放互斥锁后发送信号通知缓冲区非满。
阅读全文