Synchronization Primitive Event

suggest change

Concept

Use an Event to synchronize the scheduling of multiple coroutines.

Put simply, an event is like the gun shot at a running race: it lets the runners off the starting blocks.

Example

import asyncio

# event trigger function
def trigger(event):

print(‘EVENT SET’) event.set() # wake up coroutines waiting

# event consumers
async def consumer_a(event):

consumer_name = ‘Consumer A’ print(’{} waiting’.format(consumer_name)) await event.wait() print(’{} triggered’.format(consumer_name))

async def consumer_b(event):

consumer_name = ‘Consumer B’ print(’{} waiting’.format(consumer_name)) await event.wait() print(’{} triggered’.format(consumer_name))

# event
event = asyncio.Event()

# wrap coroutines in one future
main_future = asyncio.wait([consumer_a(event),
                            consumer_b(event)])

# event loop
event_loop = asyncio.get_event_loop()
event_loop.call_later(0.1, functools.partial(trigger, event))  # trigger event in 0.1 sec

# complete main_future
done, pending = event_loop.run_until_complete(main_future)

Output:

Consumer B waiting

Consumer A waiting

EVENT SET

Consumer B triggered

Consumer A triggered

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Asyncio Module:
* Synchronization Primitive Event

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
53 Asyncio Module
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve