Sobes.tech
Middle

Tell me about types of blocks.

sobes.tech AI

Answer from AI

In Python, there are different types of locks used for thread synchronization and to prevent race conditions:

  1. threading.Lock — a basic lock (mutex). It allows one thread to acquire the lock, while other threads wait for it to be released.

  2. threading.RLock (Reentrant Lock) — a recursive lock that can be acquired multiple times by the same thread without causing deadlock.

  3. threading.Semaphore — a counter that limits the number of threads executing a particular section of code simultaneously.

  4. threading.Event — not exactly a lock, but a mechanism to notify threads about the occurrence of an event.

  5. multiprocessing.Lock — a lock for processes, used when working with multiple processes.

Example of using threading.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 output: 10

Thus, locks help prevent simultaneous access to shared resources and ensure the correct operation of multithreaded programs.