blue-sky
blue-sky

Reputation: 53786

Async functions are unexpectedly blocking each other

I'm attempting to run two functions in separate threads that do not block each other. Each thread contains a loop.

Output of below code :

%reset -f 

import asyncio
import time

async def run1():

    for i in range(0 , 3) :
        print('run1')
        time.sleep(1)

async def run2():

    for i in range(0 , 3) :
        print('run2')
        time.sleep(2)

async def main():
    results = await asyncio.gather(
        run1() , run2())

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) 
loop.run_until_complete(main())

is :

run2
run2
run2
run1
run1
run1

But it can also be

run1
run1
run1
run2
run2
run2

So it seems that once either of thread run1 or run2 the thread blocks the other thread of starting until the current run completes.

I'm expecting output similar to :

run1
run1
run2
run2
run1
run2

How to allow threads run1 and run2 to not block each other ?

I'm using Python3.

Upvotes: 0

Views: 252

Answers (1)

georgexsh
georgexsh

Reputation: 16624

change time.sleep to corresponding asyncio version:

await asyncio.sleep(1)

and the correct result of your code is:

run1
run2
run1
run2
run1
run2

because print happens before sleep.

Upvotes: 3

Related Questions