Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向其他QThread发送消息_Python_Multithreading_Pyside_Signals Slots_Qthread - Fatal编程技术网

Python 向其他QThread发送消息

Python 向其他QThread发送消息,python,multithreading,pyside,signals-slots,qthread,Python,Multithreading,Pyside,Signals Slots,Qthread,我试图弄清楚如何实现让我的主线程生成一个新线程的概念,该线程在消息传递给它时并发处理数据 根据我目前的想法,最简单的方法是: from PySide.QtCore import QCoreApplication, QObject, Signal, QThread, QTimer class Foo(QObject): do_foo = Signal(str) def __init__(self, parent=None): super(Foo, self).

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

根据我目前的想法,最简单的方法是:

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_())

但是如果这样做的话,我看不出插槽的用途。

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

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

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

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)