使用python asyncio为什么不能从另一个线程中恢复等待中的Feture?

发布于 2022-09-12 00:22:26 字数 1190 浏览 24 评论 0

任务描述

在python中模拟一个协程任务,await一个Feture,任务提交到另一个线程,当另一个协程完成任务时Feture set_result后激活主线程中的await。

代码如下

import threading  
import time  
import asyncio  
  
loop = asyncio.get_event_loop()  
  
  
async def test_future():  
  
    f = asyncio.Future()  
  
    def sch(future):  
        print("sch begin")  
        time.sleep(1)  
        future.set_result('aaa')  
        print("sch finish")  
  
    th = threading.Thread(target=sch, args=(f,))  
    th.start()  
    y = await f  
    print("y", y)  
    return "abc"  
  
  
async def main():  
    aaa = await test_future()  
    print(aaa)  
  
  
print("start loop")  
loop.run_until_complete(main())  
print("fin")
  • 控制台输出如下
Connected to pydev debugger (build 183.5429.31)
start loop
sch begin
sch finish

疑惑及补充说明

  1. 在sch函数中feture set_result后为啥没有激活主线程中的await?
  2. 如果在y = await f那一行断点足够多时间超过time.sleep(1)时间,即待任务线程结束后,继续断点这个时候才符合预期,控制台输出如下:
Connected to pydev debugger (build 183.5429.31)
start loop
sch begin
sch finish
y aaa
abc
fin

Process finished with exit code 0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文