Junior — Middle
What is the purpose of a mutex when working with threads in Python?
sobes.tech AI
Answer from AI
A mutex (mutual exclusion) in Python is used for thread synchronization and to prevent concurrent access to shared resources. It ensures that at any given moment, only one thread can execute the critical section of code protected by this mutex.
This is important to avoid race conditions, where multiple threads modify the same data simultaneously, which can lead to unpredictable results.
An example of using a mutex with the threading module:
import threading
lock = threading.Lock()
shared_resource = 0
def increment():
global shared_resource
with lock: # Acquire the mutex
temp = shared_resource
temp += 1
shared_resource = temp
threads = [threading.Thread(target=increment) for _ in range(1000)]
for t in threads:
t.start()
for t in threads:
t.join()
print(shared_resource) # Expected to be 1000
Without a mutex, the result could be less than 1000 due to concurrent access.