[英]MultiThreading with Python
这是一个生产者消费者问题。 我需要一个生产者和多个消费者来访问共享数据单元,并且每个消费者都需要在生产者制作额外数据之前访问生产的数据。 当只有一个消费者时,代码可以正常工作。 我试图列出生产者和消费者的列表,以便对它们进行 to.join() 和 .start()。 该程序对第一个消费者有效,但在到达第二个消费者时挂断。 我试图将getData和setData中的锁定机制从“notify”更改为“notifyAll”,我是python的初学者,这些东西对我来说很陌生,但我已经尝试了10个小时,真的很感激帮助。
import time, random
from threading import Thread, currentThread, Condition
class SharedCell(object):
def __init__(self):
self.data = -1
self.writeable = True
self.condition = Condition()
def setData(self, data):
self.condition.acquire()
while not self.writeable:
self.condition.wait()
print("%s setting data to %d" % \
(currentThread().getName(), data))
self.data = data
self.writeable = False
self.condition.notifyAll()
self.condition.release()
def getData(self):
self.condition.acquire()
while self.writeable:
self.condition.wait()
print(f'accessing data {currentThread().getName()} {self.data}')
self.writeable = True
self.condition.notifyAll()
self.condition.release()
return self.data
class Producer(Thread):
def __init__(self, cell, accessCount, sleepMax):
Thread.__init__(self, name = "Producer")
self.accessCount = accessCount
self.cell = cell
self.sleepMax = sleepMax
def run(self):
print("%s starting up" % self.getName())
for count in range(self.accessCount):
time.sleep(random.randint(1, self.sleepMax))
self.cell.setData(count + 1)
print("%s is done producing\n" % self.getName())
class Consumer(Thread):
def __init__(self, cell, accessCount, sleepMax):
Thread.__init__(self)
self.accessCount = accessCount
self.cell = cell
self.sleepMax = sleepMax
def run(self):
print("%s starting up" % self.getName())
for count in range(self.accessCount):
time.sleep(random.randint(1, self.sleepMax))
value = self.cell.getData()
print("%s is done consuming\n" % self.getName())
def main():
accessCount = int(input("Enter the number of accesses: "))
sleepMax = 4
cell = SharedCell()
producer = Producer(cell, accessCount, sleepMax)
consumer = Consumer(cell, accessCount, sleepMax)
consumerTwo = Consumer(cell, accessCount, sleepMax)
threads = []
threads.append(producer)
threads.append(consumer)
threads.append(consumerTwo)
print("Starting the threads")
for thread in threads:
thread.start()
thread.join()
main()
join
function 阻塞当前线程并等待直到指示的线程终止。 在您的main
function 结束时的循环中,为什么在启动后立即join
每个线程? 这将导致启动线程 1,然后在启动线程 2 之前等待它终止,然后在启动线程 3 之前等待它终止,依此类推。
也许你的意思是这样的:
for thread in threads:
thread.start()
for thread in threads:
thread.join()
以便在您等待它们终止之前启动每个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.