无法理解的行为Future.set\u结果在另一个线程的未来

2024-10-01 13:40:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望一个类函数暂停执行,直到另一个线程根据该函数的请求更改类变量的值为止。我是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"。你知道吗

非常感谢您的帮助。你知道吗


Tags: 函数selfloopeventasynciodefservicefuture
1条回答
网友
1楼 · 发布于 2024-10-01 13:40:35

Asyncio futures不是线程安全的-也不是任何其他Asyncio API,除了whereexplicitly noted otherwise。要将未来标记为从其他线程完成,请使用^{}

self.loop.call_soon_threadsafe(self.futures[k].set_result, v)

该调用将通知事件循环发生了什么,并让事件循环设置未来的结果,立即注意到它并唤醒等待的协程。你知道吗

还要注意,对reader()asyncio.set_event_loop()的调用看起来不正确,因为事件循环实际上不是在读取器线程中运行的。你知道吗

相关问题 更多 >