2013-01-24 22 views
7

グローバル変数を使用せずに、このコードでthreadOneからthreadTwoに変数を(または変数を)送信する方法を知っている人はいますか?そうでない場合は、グローバル変数をどのように操作しますか?両方のクラスの前に定義し、実行関数でグローバル定義を使用するだけですか?クラススレッド間でメッセージを送信する

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の使用。

最初のスレッドは、ロックを取得して変数に書き込みます。

第2のスレッドは、データを待って印刷します。

更新

あなたの周りに渡されるメッセージを必要とする以上の二つのスレッドを持っている場合、threading.Conditionを使用することをお勧めします。

+1

ロックを持つグローバル変数ではなくキューを使用して、あるスレッドから別のスレッドにデータを送信するほうが賢明です。キューを使用しないとよい理由がない限り、キューから始めてください。以下の答えをGerald Kaszubaからご覧ください。 –

+0

@MarkLakataなぜ説明できますか? – ATOzTOA

+0

@マークラカタ私はなぜ同様に知ることに興味があります。 –

関連する問題