栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从虚拟线程中的调用在主线程中执行Python函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从虚拟线程中的调用在主线程中执行Python函数

您想使用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

然后永远封锁



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464444.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号