Properly respond to await condition from another context

109 Views Asked by At

If am using uvloop or asyncio, one of the features i am trying to explore is if i do some actions and then "await on a condition."

Let's look at the following example:

do_something()
zmq.send(stuff,coroutine_context)
rr = await (condition)
return rr

then some other process does some work.

then a coroutine on this process has:

rval = zmq.recv()
look at rval and get coroutine_context.
notify (condition) pass in rval.

Now i know i could use something like a condition variable but those require a lock of some kind. I do not care about multiple people accessing that coroutine so i don't want to 'lock' anything. I simply want to notify() that context with some data in this other coroutine (zmq coroutine) to return back to some element.

The key here is extracting the coroutine context (some id) to then notify the await command and pass in this rval item.

any ideas on how to do this efficiently without locks?

1

There are 1 best solutions below

2
On BEST ANSWER

This can be realized using an asyncio.Event. Create an event and pass it to both the function that should notify and the function that should await.

The awaiting side should await event.wait(). The notifying side should call event.set(). This assumes that both sides use asyncio and not threads. If the notifier is executing in a different thread, it should call loop.call_soon_threadsafe(event.set) instead.