我目前正在使用一些无尽的任务 asyncio.wait
我需要一个特殊的功能来在其他所有功能都打开时运行 await
import asyncio
async def special_function():
while True:
# does some work,
# Passes control back to controller to run main_tasks
# if they are no longer waiting.
await asyncio.sleep(0)
async def handler():
tasks = [task() for task in main_tasks]
# Adding the task that I want to run when all main_tasks are awaiting:
tasks.append(special_function())
await asyncio.wait(tasks)
asyncio.get_event_loop().run_until_complete(handler())
我如何才能special_function
仅在全部main_tasks
打开时才能运行await
?
我的意思是“所有人main_tasks
都在await
”:所有人main_tasks
都还没有准备好继续,例如处于asyncio.sleep(100)
绑定状态或I / O,仍在等待数据。
因此,main_tasks
不能继续执行,并且事件循环special_function
在任务处于此状态时运行,而不是事件循环的每次迭代。
我的用例:
将main_tasks
要更新与网络插座新数据的数据结构。
根据special_function
来自该进程的更新信号,将数据传输到另一个进程。(multiprocessing
具有共享变量和数据结构)
它必须是传输时可以提供的最新数据,并且不能有来自main_tasks的挂起更新。
这就是为什么我只想在没有main_tasks包含新数据可处理的情况下才运行special_function的原因。(即所有等待中await
)
我试图为“任务未准备好运行”条件编写测试。我认为asyncio不会公开调度程序的详细信息。开发人员明确表示,他们希望保留更改异步内部结构的自由,而又不会破坏向后兼容性。
在asyncio.Task
其中有此注释(注意:_step()
运行任务协程直到下一次等待):
# An important invariant maintained while a Task not done:
#
# - Either _fut_waiter is None, and _step() is scheduled;
# - or _fut_waiter is some Future, and _step() is *not* scheduled.
但是,该内部变量当然不在API中。
您可以_fut_waiter
通过阅读的输出来获得有限的访问权限repr(task)
,但是格式似乎也不可靠,因此我不会依赖于这种方式:
PENDINGMSG = 'wait_for=<Future pending '
if all(PENDINGMSG in repr(t) for t in monitored_tasks):
do_something()
无论如何,我认为您正在尝试变得过于完美。您想知道其他任务中是否有新数据。如果数据在异步缓冲区中怎么办?内核缓冲区?网卡接收缓冲区?...您永远无法知道新数据是否会在下一毫秒到达。
我的建议:将所有更新写入单个队列。检查该队列作为唯一的更新源。如果队列为空,则发布最后一个状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句