我希望一个类函数暂停执行,直到另一个线程根据该函数的请求更改类变量的值为止。我是python异步模块的新手。你知道吗
你知道吗异步。未来似乎提供了一种等待未来价值的机制,因此我尝试了以下一个玩具示例:
class RandomReader:
def __init__(self):
self.loop = asyncio.get_event_loop()
self.service = 3
self.thread = threading.Thread(target=self.reader)
self.thread.start()
self.futures: Dict[int, asyncio.Future] = {}
def reader(self):
asyncio.set_event_loop(self.loop)
while self.service != 0:
k, v = read()
if k in self.futures:
if self.futures[k].done():
continue
self.futures[k].set_result(v)
self.service -= 1
async def wait(self, v: int):
self.futures[v] = self.loop.create_future()
a = await self.futures[v]
logging.debug("value %d received %f", v, a)
return v, a
上面的read
函数读取可能与wait
匹配的随机键和值。你知道吗
调用函数进行如下3次调用(RandomReader.service
)
t1 = asyncio.create_task(random_reader.wait(3))
print(await t1)
我希望self.futures[k].set_result(v)
将值赋给wait
函数中的a
,就像Future
对象的documentation,但是等待实际上没有执行。尽管期货在self.futures
中的状态确实变为"FINISHED"
。你知道吗
非常感谢您的帮助。你知道吗
Asyncio futures不是线程安全的-也不是任何其他Asyncio API,除了whereexplicitly noted otherwise。要将未来标记为从其他线程完成,请使用^{} :
该调用将通知事件循环发生了什么,并让事件循环设置未来的结果,立即注意到它并唤醒等待的协程。你知道吗
还要注意,对
reader()
中asyncio.set_event_loop()
的调用看起来不正确,因为事件循环实际上不是在读取器线程中运行的。你知道吗相关问题 更多 >
编程相关推荐