我正在尝试创建一个简单的程序,该程序使用套接字等待文件,然后将其输出返回到另一个线程上的文本字段。
我做了一些研究,我知道线程的基础知识是如何工作的,但我不明白多个线程如何相互连接。
我的问题是该WindowManager.addText函数仅在类本身的事件上更新WindowManager,而不是从ConnectionManager类中更新。我该如何解决这个问题,以便每次WindowManager.addText在另一个线程上调用它都会立即更新?
我有一个WindowManager类,它将一个字符串保存到一个文本字段(用 GTK 加载):
class WindowManager:
    def __init__(self):
        #Load the window here, not relevant
        self.textBuffer = self.messagePanel.get_buffer()
        self.lock = threading.Lock()
    def addText(self, text, *args):
        self.lock.acquire()        
        logging.debug('Waiting for lock')
        try:
            logging.debug('Acquired lock')
            self.textBuffer.insert_with_tags_by_name(self.textBuffer.get_end_iter(), text, *args)
        finally:
            self.lock.release()
现在我ConnectionManager这里也有一个类,它加载连接线程:
class ConnectionManager:
    def __init__(self, windowManager):
        self.ping = PingThread(windowManager)
        self.ping.setDaemon(True)
        self.ping.start()
最后我得到了PingThread实际连接线程的类,在这个例子中我随机调用线程:
class PingThread(threading.Thread):
    def __init__(self,  window, group=None, target=None, name=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
        self.window = window
    def run(self):
        while True:
            self.window.addText("Test")
            time.sleep(random.randrange(1,10))