Skip to content
This repository was archived by the owner on Nov 23, 2017. It is now read-only.
This repository was archived by the owner on Nov 23, 2017. It is now read-only.

Race condition in asyncio.wait_for() #343

@jihoonyoon

Description

@jihoonyoon

In the following program, the prod coroutine produces 0 to 5 and put them into the queue, and the cons coroutine consumes them with timeout. If this program is run, the cons gets item 0, 1, 2, 3, and 5, but not 4. In other words, the item 4 was put into the queue, but it got lost.

It seems that the observed behavior happens because the _release_waiter function does not cancel fut, opening up a potential race condition in which fut progresses even after the waiter is released.

  • Program
import asyncio, time

@asyncio.coroutine
def prod(q, loop):
    for i in range(6):
        print("putting an item=%s" % i)
        yield from q.put(i)
        yield from asyncio.sleep(i)
    yield from q.put(None)

@asyncio.coroutine
def cons(q, loop):
    while True:
        try:
            item = yield from asyncio.wait_for(q.get(), 3.0)
            print("got an item=%s" % item)
        except asyncio.TimeoutError as e:
            print("timeout!")
            continue
        if item == None: break
    loop.stop()

loop = asyncio.get_event_loop()
q = asyncio.Queue()
loop.create_task(prod(q, loop))
loop.create_task(cons(q, loop))
loop.run_forever()
  • Output
putting an item=0
putting an item=1
got an item=0 <------ 1 received
got an item=1
putting an item=2
got an item=2 <------ 2 received
putting an item=3
got an item=3 <------ 3 received
putting an item=4
timeout!
timeout!               
putting an item=5
got an item=5 <------ 5 received, but where 4 went?
timeout!
got an item=None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions