Channel Synchronization in Python
This example demonstrates how to use threading for synchronization in Python. We’ll create a function that runs in a separate thread and use an Event
object to notify the main thread when it’s finished.
import threading
import time
# This is the function we'll run in a separate thread. The
# 'done' event will be used to notify the main thread that
# this function's work is done.
def worker(done):
print("working...", end="", flush=True)
time.sleep(1)
print("done")
# Set the event to notify that we're done.
done.set()
def main():
# Create an event for synchronization
done = threading.Event()
# Start a worker thread, passing it the event to set when it's done
thread = threading.Thread(target=worker, args=(done,))
thread.start()
# Block until we receive a notification from the worker thread
done.wait()
if __name__ == "__main__":
main()
To run the program:
$ python channel_synchronization.py
working...done
In this Python version:
We import the
threading
module for thread-related operations and thetime
module for the sleep function.The
worker
function simulates work by printing a message, sleeping for a second, and then printing “done”. It sets thedone
event when it finishes.In the
main
function, we create athreading.Event
object. This is similar to a channel in the original example, used for synchronization between threads.We start a new thread that runs the
worker
function, passing it thedone
event.The main thread then waits for the worker thread to finish by calling
done.wait()
. This blocks until the event is set.If you removed the
done.wait()
line from this program, the main thread would exit before the worker thread even started its work.
This approach demonstrates how to use threading and events in Python to synchronize execution across different threads, which is conceptually similar to using goroutines and channels in the original example.