| In Python, the threading module provides the necessary tools for working with threads and locks (mutexes). In this example, we'll create a simple counter that is incremented by multiple threads. We'll use a mutex to ensure that the counter is updated safely. import threading
# Shared resource
counter = 0
# Mutex lock
lock = threading.Lock()
# Function to be executed by each thread
def increment_counter():
global counter
for _ in range(1000):
with lock:
counter += 1
# List to keep track of threads
threads = []
# Create and start 10 threads
for i in range(10):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads:
thread.join()
# Print the final value of the counter
print(f"Final counter value: {counter}")
Explanation - Shared Resource:
counter is the shared resource that the threads will increment. - Mutex Lock:
lock is a mutex that will ensure only one thread can modify the counter at a time. - Thread Function:
increment_counter is the function executed by each thread. It increments the counter 1000 times. The with lock statement ensures that only one thread can increment the counter at a time. - Thread Creation and Start: We create 10 threads and start them.
- Wait for Threads to Finish: We use
join to wait for all threads to finish. - Final Counter Value: After all threads have finished, we print the final value of the counter.
This ensures that the counter is incremented safely without any race conditions.  |