简体   繁体   English

如何使事件循环同时运行任务?

[英]How to make event loop run task concurrently?

I want to call two function concurrently in asyncio , I do it with loop.create_task , but I find that it is not concurrently actually.我想在 asyncio 中同时调用两个asyncio ,我用loop.create_task ,但我发现它实际上不是并发的。

Here is my code:这是我的代码:

import asyncio


async def foo(v):
    print(f"start {v}")
    for i in range(5):
        print(f"work in {v}")
    print(f"done {v}")


def schedule_foo():
    print("out start 1")
    loop.create_task(foo(1))
    print("out start 2")
    loop.create_task(foo(2))


loop = asyncio.get_event_loop()
schedule_foo()
loop.run_forever()

this will output:这将是 output:

out start 1
out start 2
start 1
work in 1
work in 1
work in 1
work in 1
work in 1
done 1
start 2
work in 2
work in 2
work in 2
work in 2
work in 2
done 2

As you can see the main loop is async, but sub task is actually sync.如您所见,主循环是异步的,但子任务实际上是同步的。

My question is how can I make the function run in concurrently actually ?我的问题是how can I make the function run in concurrently actually

You forgot to use await :你忘了使用await

import asyncio

async def foo(v):
    print(f"start {v}")
    for i in range(5):
        print(f"work in {v}")
        await asyncio.sleep(0.1)
    print(f"done {v}")


def schedule_foo():
    print("out start 1")
    loop.create_task(foo(1))
    print("out start 2")
    loop.create_task(foo(2))


loop = asyncio.get_event_loop()
schedule_foo()
loop.run_forever()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM