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...doneIn this Python version:
We import the
threadingmodule for thread-related operations and thetimemodule for the sleep function.The
workerfunction simulates work by printing a message, sleeping for a second, and then printing “done”. It sets thedoneevent when it finishes.In the
mainfunction, we create athreading.Eventobject. This is similar to a channel in the original example, used for synchronization between threads.We start a new thread that runs the
workerfunction, passing it thedoneevent.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.