2013-01-24 31 views
7

有沒有人知道如何在不使用全局變量的情況下將代碼中的變量(或變量)從threadOne發送到threadTwo?如果不是,我將如何操作一個全局變量?只需在兩個類之前定義它並在運行函數中使用全局定義?在類線程之間發送消息Python

import threading 

print "Press Escape to Quit" 

class threadOne(threading.Thread): #I don't understand this or the next line 
    def run(self): 
     setup() 

    def setup(): 
     print 'hello world - this is threadOne' 


class threadTwo(threading.Thread): 
    def run(self): 
     print 'ran' 

threadOne().start() 
threadTwo().start() 

感謝

回答

14

您可以使用queues在一個線程安全的方式發送線程之間的消息。

def worker(): 
    while True: 
     item = q.get() 
     do_work(item) 
     q.task_done() 

q = Queue() 
for i in range(num_worker_threads): 
    t = Thread(target=worker) 
    t.daemon = True 
    t.start() 

for item in source(): 
    q.put(item) 

q.join()  # block until all tasks are done 
+0

我是否在類的外面定義這些? –

+0

你應該在開始使用它們之前創建隊列,所以是的,在線程類之外/之前。 –

4

在這裏,使用Lock

import threading 

print "Press Escape to Quit" 

# Global variable 
data = None 

class threadOne(threading.Thread): #I don't understand this or the next line 
    def run(self): 
     self.setup() 

    def setup(self): 
     global data 
     print 'hello world - this is threadOne' 

     with lock: 
      print "Thread one has lock" 
      data = "Some value" 


class threadTwo(threading.Thread): 
    def run(self): 
     global data 
     print 'ran' 
     print "Waiting" 

     with lock: 
      print "Thread two has lock" 
      print data 

lock = threading.Lock() 

threadOne().start() 
threadTwo().start() 

使用全局變量data

第一個線程獲取鎖並寫入變量。

第二個線程等待數據並打印它。

更新

如果有兩個以上的線程這​​就需要消息被傳來傳去,最好是使用threading.Condition

+1

使用隊列而不是帶全局變量的鎖來將數據從一個線程發送到另一個線程通常會更好。你應該從一個隊列開始,除非有一個很好的理由*不*使用一個。請參閱以下來自Gerald Kaszuba的回答 –

+0

@MarkLakata你能解釋一下爲什麼嗎? – ATOzTOA

+0

@MarkLakata我很想知道爲什麼。 –