您想使用Queue(现在是python
3的队列)类来设置一个队列,您的虚拟线程将使用函数填充该队列,而主线程会使用该队列。
import Queue#somewhere accessible to both:callback_queue = Queue.Queue()def from_dummy_thread(func_to_call_from_main_thread): callback_queue.put(func_to_call_from_main_thread)def from_main_thread_blocking(): callback = callback_queue.get() #blocks until an item is available callback()def from_main_thread_nonblocking(): while True: try: callback = callback_queue.get(False) #doesn't block except Queue.Empty: #raised when queue is empty break callback()
演示:
import threadingimport timedef print_num(dummyid, n): print "From %s: %d" % (dummyid, n)def dummy_run(dummyid): for i in xrange(5): from_dummy_thread(lambda: print_num(dummyid, i)) time.sleep(0.5)threading.Thread(target=dummy_run, args=("a",)).start()threading.Thread(target=dummy_run, args=("b",)).start()while True: from_main_thread_blocking()印刷品:
From a: 0From b: 0From a: 1From b: 1From b: 2From a: 2From b: 3From a: 3From b: 4From a: 4
然后永远封锁



