首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向其他QThread发送消息

向其他QThread发送消息
EN

Stack Overflow用户
提问于 2014-03-04 00:17:48
回答 1查看 582关注 0票数 1

我正在试图弄清楚如何实现让我的主线程产生一个新线程的概念,该线程在消息传递到主线程时并发地处理数据。

到目前为止,我认为最简单的方法是这样做:

代码语言:javascript
复制
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_())

但是,如果这是这样做的话,我看不出Slots的用处。

EN

回答 1

Stack Overflow用户

发布于 2014-03-04 02:31:14

或者你可以使用“提供者-消费者”的设计模式。它是如何工作的?嗯,你必须实现一个queue扩展线程将从该queue获取数据,而主线程将向queue提供新数据。

当队列为空时,生成的线程会阻塞。这样,您甚至可以在多个线程中处理数据,并且不必担心两个线程试图读取相同的数据。

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

代码语言:javascript
复制
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)

然后在你的main thread

代码语言:javascript
复制
import Queue
queue = Queue.Queue()
mthread = MyThread(queue)
mthread.start()

# And now you can send data to threads by:
queue.put(data)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22151737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档