gpt4 book ai didi

python - await 似乎阻塞了 asyncio.Future

转载 作者:行者123 更新时间:2023-12-05 07:23:48 25 4
gpt4 key购买 nike

我正在尝试理解 python async/await 并使用 Future 对象来指示函数可以继续。这是一些重现我遇到的问题的代码:

import time, threading, asyncio

loop = asyncio.get_event_loop()
f = loop.create_future()

def resolve(fut):
for i in range(3):
print(i)
time.sleep(1)
fut.set_result(88)

async def wait_on_future(fut):
print('waiting for fut')
await fut
print('done', fut.result())
return fut.result()

threading.Thread(target=resolve, args=(f,)).start()
loop.create_task(wait_on_future(f))
loop.run_forever()

打印:

0
waiting for fut
1
2

请注意,它从不打印 'done'。在awaitables文档的一部分,它说:

When a Future object is awaited it means that the coroutine will wait until the Future is resolved in some other place.

我认为调用set_result 是解析Future 的方法。我在这里缺少什么?

注意:如果我在同一个线程中调用 resolve,则可以正常工作。我试图解决的实际问题是碰巧解决 Future 的事件在一个线程中。我确实注意到 Future文档说它不是线程安全的。如何创建等待另一个线程中发生的事件的异步函数?

最佳答案

好的,感谢@CharmingRobot 关于 run_coroutine_threadsafe 的评论,我得出了这个解决方案:

import time, threading, asyncio

loop = asyncio.get_event_loop()
f = loop.create_future()

def resolve(fut):
for i in range(3):
print(i)
time.sleep(1)
async def a_resolve():
fut.set_result(88)
asyncio.run_coroutine_threadsafe(a_resolve(), loop)

async def wait_on_future(fut):
print('waiting for fut')
return await fut

async def print_future():
print('got the future! value:', await wait_on_future(f))

loop.create_task(print_future())
threading.Thread(target=resolve, args=(f,)).start()
loop.run_forever()

打印:

0
waiting for fut
1
2
got the future! value: 88

这正是我要找的。

关于python - await 似乎阻塞了 asyncio.Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55768832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com