Junior — Middle
Can you name the main mechanisms and tools for organizing thread or process synchronization?
sobes.tech AI
Answer from AI
Main mechanisms and tools for thread or process synchronization in Python:
- Lock: Ensures mutual exclusion so that only one thread can execute a critical section.
- RLock (reentrant lock): Allows a thread to acquire the lock multiple times.
- Semaphore: Limits the number of threads that can access a resource 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.
- Queue: Thread-safe queue for data exchange between threads.
For processes (module multiprocessing), there are similar mechanisms:
multiprocessing.Lock,multiprocessing.Semaphore,multiprocessing.Event,multiprocessing.Queue.
Example of using Lock:
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
with lock:
temp = counter
temp += 1
counter = temp
threads = [threading.Thread(target=increment) for _ in range(100)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # Should be 100