这是生产者的消费者问题。我需要一个生产者和多个使用者来访问共享数据单元,每个使用者需要在生产者生成额外数据之前访问生成的数据。当有一个使用者时,代码可以正常工作。为了.join()和.start(),我尝试列出生产者和消费者的列表。该程序对于第一个用户来说是有效的,但是当它到达第二个消费者时就会挂断。我尝试将getData和setData中的锁定机制从“通知”更改为“setData”,我是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()发布于 2021-12-06 19:51:54
join函数阻塞当前线程,并等待指示线程终止。在main函数末尾的循环中,为什么在启动每个线程之后立即执行join?这将导致启动线程1,然后等待它在启动线程2之前终止,然后等待它在启动线程3之前终止,依此类推。
也许你的意思是这样的:
for thread in threads:
thread.start()
for thread in threads:
thread.join()以便在等待线程终止之前启动每个线程。
https://stackoverflow.com/questions/70251104
复制相似问题