简体   繁体   English

多线程与 Python

[英]MultiThreading with Python

This is a Producer Consumer Problem.这是一个生产者消费者问题。 I need a single producer and multiple consumers to access the shared data cell and each consumer needs to access the produced data before the producer makes additional data.我需要一个生产者和多个消费者来访问共享数据单元,并且每个消费者都需要在生产者制作额外数据之前访问生产的数据。 The code works fine when there is a single consumer.当只有一个消费者时,代码可以正常工作。 I have attempted to make a list of the Producer and Consumers in order to.join() and.start() them.我试图列出生产者和消费者的列表,以便对它们进行 to.join() 和 .start()。 The program works so far as the first consumer, but hangs up when it gets to the second consumer.该程序对第一个消费者有效,但在到达第二个消费者时挂断。 I have tried to change the locking mechanisms from "notify" to "notifyAll" in the getData and setData, I am a beginner in python and this stuff is pretty foreign to me but I have been trying stuff for 10 hours and would really appreciate some help.我试图将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()

The join function blocks the current thread and waits until the indicated thread terminates. join function 阻塞当前线程并等待直到指示的线程终止。 In your loop at the end of your main function, why do you join each thread immediately after starting it?在您的main function 结束时的循环中,为什么在启动后立即join每个线程? That would result in starting thread 1, and then waiting for it to terminate before starting thread 2, and then waiting that it to terminate before starting thread 3, and so on.这将导致启动线程 1,然后在启动线程 2 之前等待它终止,然后在启动线程 3 之前等待它终止,依此类推。

Perhaps you meant something like this:也许你的意思是这样的:

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

so that every thread is started before you wait for them to terminate.以便在您等待它们终止之前启动每个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM