如何在 Python 中的 运行 线程中更改或调用方法?

How to make changes to or call a method in a running thread in Python?

我有一个生产者线程,它从串行连接中产生数据,并将它们放入多个队列中,供不同的消费者线程使用。但是,我希望能够在生产者线程已经启动 运行ning 之后从主线程添加额外的队列(额外的消费者)。

即在下面的代码中,当主线程处于 运行ning 状态时,如何从主线程向 listOfQueues 添加队列?我可以将 addQueue(newQueue) 之类的方法添加到附加到它 listOfQueues 的 class 中吗?这似乎不太可能,因为线程将在 运行 方法中。我可以创建某种类似于停止事件的事件吗?

class ProducerThread(threading.Thread):
    def __init__(self, listOfQueues):
        super(ProducerThread, self).__init__()
        self.listOfQueues = listOfQueues
        self._stop_event = threading.Event() # Flag to be set when the thread should stop

    def run(self):
        ser = serial.Serial() # Some serial connection 

        while(not self.stopped()):
            try:
                bytestring = ser.readline() # Serial connection or "producer" at some rate
                for q in self.listOfQueues:
                    q.put(bytestring)
            except serial.SerialException:
                continue

    def stop(self):
        '''
        Call this function to stop the thread. Must also use .join() in the main
        thread to fully ensure the thread has completed.
        :return: 
        '''
        self._stop_event.set()

    def stopped(self):
        '''
        Call this function to determine if the thread has stopped. 
        :return: boolean True or False
        '''
        return self._stop_event.is_set()

当然,您可以简单地使用添加到列表中的附加功能。例如

def append(self, element):
    self.listOfQueues.append(element)

即使在您的线程的 start() 方法被调用后,这仍然有效。

编辑: 对于非线程安全程序,您可以使用锁,例如:

def unsafe(self, element):
    with self.lock:
        # do stuff

然后您还需要在 run 方法中添加锁,例如:

with lock:
    for q in self.listOfQueues:
        q.put(bytestring)

任何获取锁的代码都将等待其他地方释放锁。