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

asyncio:是否可以取消由执行者执行的未来?

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

asyncio:是否可以取消由执行者执行的未来?

在这种情况下,

Future
一旦它真正开始运行,就无法取消它,因为您依赖的行为
concurrent.futures.Future
,并且它的文档指出以下内容:

cancel()

尝试取消呼叫。 如果该调用当前正在执行并且无法取消,则该方法将返回

False
,否则,该调用将被取消并且该方法将返回
True

因此,唯一成功的取消操作是如果任务仍在中等待执行

Executor
。现在,您实际上正在使用
asyncio.Future
包裹
concurrent.futures.Future
,并且在实践中,即使基础任务实际上已经在运行,如果您在调用后尝试
asyncio.Future
返回,by
loop.run_in_executor()
也会引发a
。但是,它 实际上 并不会取消中的任务执行。
CancellationError``yield from``cancel()
__
Executor

如果需要实际取消任务,则需要使用更常规的方法来中断线程中正在运行的任务。具体操作方式取决于用例。对于示例中显示的用例,可以使用

threading.Event

def blocking_func(seconds_to_block, event):    for i in range(seconds_to_block):        if event.is_set(): return        print('blocking {}/{}'.format(i, seconds_to_block))        time.sleep(1)    print('done blocking {}'.format(seconds_to_block))...event = threading.Event()blocking_future = loop.run_in_executor(None, blocking_func, 5, event)print('wait a few seconds!')yield from asyncio.sleep(1.5)blocking_future.cancel()  # Mark Future as cancelledevent.set() # Actually interrupt blocking_func


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

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

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