Sobes.tech
Junior — Middle

What methods of thread synchronization do you know in Python?

sobes.tech AI

Answer from AI

In Python, various mechanisms from the threading module are used for thread synchronization:

  • Lock (mutex) — a basic primitive for mutual exclusion, allowing one thread to acquire a resource, blocking access to others.

  • RLock (reentrant lock) — similar to Lock, but the same thread can acquire it multiple times without deadlock.

  • Semaphore — limits the number of threads that can access a resource simultaneously.

  • Event — allows one thread to notify others about the occurrence of an event.

  • Condition — a more complex primitive that allows threads to wait for a certain condition and notify each other.

Example of using Lock:

import threading

lock = threading.Lock()
shared_resource = 0

def worker():
    global shared_resource
    with lock:
        # Critical section
        shared_resource += 1

threads = [threading.Thread(target=worker) for _ in range(10)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(shared_resource)  # Expected 10

These mechanisms help prevent data races and ensure correct thread interaction.