Issue
I wrote the following code:
import asyncio
async def write_after(pause,text):
print('begin')
await asyncio.sleep(pause)
print(text)
async def main():
await write_after(1,'Hello...')
await write_after(2,'...world')
asyncio.run(main())
As result I got:
begin
Hello...
begin
...world
with pauses right after begin
s. I was wondering why result isn't:
begin
begin
Hello...
...world
like executing program that uses tasks.
Solution
Basically what's happening is you're waiting for the first result to finish, then starting the second function call and waiting for that result. I think what you're expecting is something like this:
import asyncio
async def write_after(pause,text):
print('begin')
await asyncio.sleep(pause)
print(text)
async def main():
await asyncio.gather(
write_after(1,'Hello...'),
write_after(2,'...world')
)
asyncio.run(main())
This will launch both coroutines concurrently and wait for the results of each. The result will be:
begin
begin
Hello...
...world
Answered By - kingkupps
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.