0

I was wondering how concurrency works in python 3.6 with asyncio. My understanding is that when the interpreter executing await statement, it will leave it there until the awaiting process is complete and then move on to execute the other coroutine task. But what I see here in the code below is not like that. The program runs synchronously, executing task one by one.

What is wrong with my understanding and my impletementation code?


    import asyncio
    import time

    async def myWorker(lock, i):
        print("Attempting to attain lock {}".format(i))
        # acquire lock
        with await lock:
            # run critical section of code
            print("Currently Locked")

            time.sleep(10)

        # our worker releases lock at this point
        print("Unlocked Critical Section")

    async def main():
        # instantiate our lock
        lock = asyncio.Lock()
        # await the execution of 2 myWorker coroutines 
        # each with our same lock instance passed in 
        # await asyncio.wait([myWorker(lock), myWorker(lock)])
        tasks = []

        for i in range(0, 100):
            tasks.append(asyncio.ensure_future(myWorker(lock, i)))

        await asyncio.wait(tasks)


    # Start up a simple loop and run our main function
    # until it is complete
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    print("All Tasks Completed")
    loop.close()

2 Answers 2

2

Invoking a blocking call such as time.sleep in an asyncio coroutine blocks the whole event loop, defeating the purpose of using asyncio.

Change time.sleep(10) to await asyncio.sleep(10), and the code will behave like you expect.

Sign up to request clarification or add additional context in comments.

3 Comments

Except that all the coroutines want the same lock, so the lock is going to keep things synchronous anyway.
@user2357112 No argument here, but that's presumably the behavior the OP expected - why would they otherwise have inserted an explicit lock?
@user4815162342 wow! that was really the problem. So that is the reason why the asynchronous thing didn't work, because the loop is blocked. Thankyou for your answer bro.
0

asyncio use a loop to run everything, await would yield back the control to the loop so it can arrange the next coroutine to run.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.