小编典典
您想使用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 threading
import time
def print_num(dummyid, n):
print "From %s: %d" % (dummyid, n)
def dummy_run(dummyid):
for i in xrange(5):
from_dummy_thread(lambda: pr