是否有人知道在不使用全局变量的情况下,如何在代码中将变量(或获取变量)从threadone发送到thread2?如果不是,如何操作全局变量?只需在两个类之前定义它并在运行函数中使用全局定义?
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()
谢谢
最佳答案
可以使用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