2014-03-03 63 views
1

我想弄清楚如何實現讓我的主線程產生一個新的線程同時處理數據的消息傳遞給它的概念的概念。發送消息給其他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).__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 s就什麼。

回答

1

或者你可以使用設計模式「提供者 - 消費者」。怎麼運行的?那麼你必須執行queuespwaned線程將從此queue獲得數據,而您的主線程將爲queue提供新數據。

enter image description here

你產生的線程塊,而隊列爲空。這樣,您甚至可以在多個線程中處理數據,而且您不必擔心兩個線程試圖讀取相同的數據。

這是消費者線程的一些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) 

然後在您的main thread

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

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