12

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

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

ありがとう

4

2 に答える 2

31

キューを使用して、スレッドセーフな方法でスレッド間でメッセージを送信できます。

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
于 2013-01-24T19:14:18.700 に答える
7

を使用して、ここに行きます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番目のスレッドはデータを待機して出力します。

アップデート

メッセージを渡す必要のあるスレッドが3つ以上ある場合は、を使用することをお勧めしますthreading.Condition

于 2013-01-24T19:17:49.260 に答える