from PyQt5.QtCore import QCoreApplication, QMutex, QThread, QWaitCondition
DataSize = 1000000
BufferSize = 8192
buffer = ['0' for x in range(BufferSize)]
bufferNotEmpty = QWaitCondition()
bufferNotFull = QWaitCondition()
mutex = QMutex()
numUsedBytes = 0
class Producer(QThread):
def __init__(self):
super().__init__()
def run(self):
global numUsedBytes
for i in range(DataSize):
mutex.lock()
if numUsedBytes == BufferSize:
bufferNotFull.wait(mutex)
mutex.unlock()
print("produce ", i)
buffer[i % BufferSize] = i
mutex.lock()
numUsedBytes += 1
bufferNotEmpty.wakeAll()
mutex.unlock()
class Consumer(QThread):
def __init__(self):
super().__init__()
def run(self):
global numUsedBytes
for i in range(Data
PyQt实现的生产者消费者模型
最新推荐文章于 2022-11-22 15:26:08 发布
本文通过PyQT展示了如何实现一个生产者消费者模型。利用QWaitCondition和QMutex,创建了Producer和Consumer两个线程,Producer负责生成数据并填满缓冲区,Consumer则消费缓冲区中的数据。当缓冲区满时,生产者会等待,直到消费者消费数据;反之,当缓冲区空时,消费者会等待新的数据。整个过程保证了线程安全。
摘要由CSDN通过智能技术生成