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.
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:
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
?
You forgot to use 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.