相关疑难解决方法(0)

Asyncio How do you use run_forever?

What I want to do:

  1. have an asyncio event loop that gets spun up
  2. that loop is passed to various classes in my system for scheduling coroutines on
  3. that loop is also used for handling the responses to events (ie, I have a Queue, some event handling code will place an item on that queue, and separate co-routines that await a get() on that queue to handle those values)
  4. there is a main thread which "owns" the loop and is …

python python-asyncio

7
推荐指数
1
解决办法
8808
查看次数

任务添加到不同线程中的空循环时的奇怪行为

我有一个应用程序,它将协同程序添加到已经运行的事件循环中.这些协同程序的参数依赖于I/O,并且在我最初启动事件循环时不可用 - 使用loop.run_forever(),所以我稍后添加任务.为了演示这种现象,这里有一些示例代码:

import asyncio
from threading import Thread
from time import sleep

loop = asyncio.new_event_loop()

def foo():
    loop.run_forever()

async def bar(s):
    while True:
        await asyncio.sleep(1)
        print("s")

#loop.create_task(bar("A task created before thread created & before loop started"))
t = Thread(target=foo)
t.start()
sleep(1)
loop.create_task(bar("secondary task"))
Run Code Online (Sandbox Code Playgroud)

奇怪的行为是,当调用loop.run_forever()时,循环中至少有一个任务时,一切都按预期工作.即当注释行没有被注释掉时.

但是当它被注释掉时,如上所示,没有打印任何内容,看起来我无法向event_loop添加任务.我应该避免在不添加单个任务的情况下调用run_forever()吗?我不明白为什么这应该是一个问题.在运行后将任务添加到event_loop是标准的,为什么空案例会成为问题?

python python-asyncio

2
推荐指数
1
解决办法
294
查看次数

标签 统计

python ×2

python-asyncio ×2