向其他QThread发送消息

1 投票
1 回答
730 浏览
提问于 2025-04-17 20:38

我正在尝试弄明白如何让我的主线程创建一个新线程,这个新线程可以同时处理数据,也就是说,当消息传递给它时,它可以同时进行处理。

到目前为止,我觉得最简单的方法可能是这样的:

from PySide.QtCore import QCoreApplication, QObject, Signal, QThread, QTimer


class Foo(QObject):
    do_foo = Signal(str)

    def __init__(self, parent=None):
        super(Foo, self).__init__(parent)
        self.do_foo.connect(self._do_foo)

    def foo(self, string):
        self.do_foo.emit(string)

    def _do_foo(self, string):
        # Process string
        print "Process thread:", self.thread().currentThreadId()


class App(QCoreApplication):
    def run(self):
        print "Main thread:", self.thread().currentThreadId()
        thread = QThread()
        foo = Foo()
        foo.moveToThread(thread)
        thread.start()

        # Obviously the following should be done with the event-loop
        # or at doing processing of events.
        running = True
        while running:
            try:
                string = raw_input()
                foo.foo(string)
            except EOFError:
                running = False

        thread.exit()
        thread.wait()
        self.exit()

if __name__ == '__main__':
    import sys
    app = App(sys.argv)
    QTimer.singleShot(0, app.run)
    sys.exit(app.exec_())

但是如果这样做的话,我就不明白Slot的作用是什么了。

1 个回答

1

或者你可以使用一种叫“提供者-消费者”的设计模式。这是怎么回事呢?简单来说,你需要实现一个 队列。被创建的线程会从这个 队列 中获取数据,而你的 主线程 则负责往 队列 中添加新数据。

在这里输入图片描述

队列 为空时,你的被创建线程会被阻塞,也就是说它会停下来等数据。这种方式允许你使用多个线程来处理数据,而且你不需要担心两个线程会同时读取同一份数据。

下面是一些消费者线程的伪代码。

class MyThread:
    def __init__(self, queue):
        self.queue = queue
        self.event = Event()    # I generally use threading.Event for stopping threads. You don't need it here.

   def run():
       while not self.event.isSet():
          data = self.queue.get()   # This stop the thread until new data be available.
          do_something_with_data(data)

然后在你的 主线程 中:

import Queue
queue = Queue.Queue()
mthread = MyThread(queue)
mthread.start()

# And now you can send data to threads by:
queue.put(data)

撰写回答