Select in Python
Python’s select
functionality can be simulated using the select
module. This example demonstrates how to wait on multiple channel-like operations, which in Python are implemented using queues and threads.
import queue
import threading
import time
def main():
# For our example we'll select across two queues.
q1 = queue.Queue()
q2 = queue.Queue()
# Each queue will receive a value after some amount
# of time, to simulate e.g. blocking RPC operations
# executing in concurrent threads.
def worker1():
time.sleep(1)
q1.put("one")
def worker2():
time.sleep(2)
q2.put("two")
threading.Thread(target=worker1).start()
threading.Thread(target=worker2).start()
# We'll use a loop with a timeout to simulate 'select'
# and await both of these values simultaneously,
# printing each one as it arrives.
for _ in range(2):
while True:
try:
msg1 = q1.get_nowait()
print("received", msg1)
break
except queue.Empty:
pass
try:
msg2 = q2.get_nowait()
print("received", msg2)
break
except queue.Empty:
pass
time.sleep(0.1) # Small delay to prevent busy waiting
if __name__ == "__main__":
main()
To run the program:
$ python select_example.py
received one
received two
Note that the total execution time is only ~2 seconds since both the 1 and 2 second sleep
operations execute concurrently.
This Python implementation uses threads and queues to simulate the concurrent behavior of goroutines and channels in the original example. The select
-like functionality is achieved by repeatedly checking both queues in a loop until a value is received.
While Python doesn’t have a built-in select
statement for synchronization like some other languages, this approach provides similar functionality for waiting on multiple concurrent operations.