在Python中在线程间发送消息
有没有人知道我怎么能在这段代码中把一个变量从线程一(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()
谢谢
2 个回答
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
。
第一个线程获取了锁,然后写入这个变量。
第二个线程在等待数据,并将其打印出来。
更新
如果你有超过两个线程需要传递消息,使用 threading.Condition
会更好。
37
你可以使用队列来在不同的线程之间安全地发送消息。
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