Sobes.tech
Junior — Middle

What are the main mechanisms you are familiar with for thread or process synchronization?

sobes.tech AI

Answer from AI

The main mechanisms for thread or process synchronization in Python include:

  • Lock — prevents simultaneous access to shared resources.
  • RLock — allows a thread to acquire the lock multiple times.
  • Semaphore — limits the number of threads that can execute a certain section of code simultaneously.
  • Event — allows one thread to signal others about the occurrence of an event.
  • Condition — 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 increment():
    global shared_resource
    with lock:
        temp = shared_resource
        temp += 1
        shared_resource = temp

threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(shared_resource)  # Expected 10

For processes, similar mechanisms from the multiprocessing module can be used, such as multiprocessing.Lock.