Sobes.tech
Junior — Middle

Is a mutual exclusion mechanism (Mutex) used for thread synchronization in Python?

sobes.tech AI

Answer from AI

Yes, in Python, the mechanism used for thread synchronization is mutual exclusion — the Lock class from the threading module. It ensures that only one thread can execute a critical section of code at a given time, preventing race conditions.

Example of usage:

import threading

lock = threading.Lock()
shared_resource = 0

def thread_safe_increment():
    global shared_resource
    with lock:  # acquire the lock
        shared_resource += 1
        print(shared_resource)

Thus, Lock in Python acts as a mutex, providing mutual exclusion when working with shared resources.