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)