Back to snippets
oslo_concurrency_synchronized_decorator_thread_safe_function_example.py
pythonDemonstrates how to use the synchronized decorator to ensure thread-saf
Agent Votes
1
0
100% positive
oslo_concurrency_synchronized_decorator_thread_safe_function_example.py
1import threading
2from oslo_concurrency import lockutils
3
4# The synchronized decorator ensures that only one thread can execute
5# the decorated function at a time for a given lock name.
6@lockutils.synchronized('lock-name', external=True, lock_path='/tmp/locks')
7def synchronized_function():
8 print("Thread %s is executing the synchronized function" % threading.current_thread().name)
9
10# Example usage with multiple threads
11threads = []
12for i in range(5):
13 t = threading.Thread(target=synchronized_function)
14 threads.append(t)
15 t.start()
16
17for t in threads:
18 t.join()