Sobes.tech
Junior — Middle

Are you familiar with data processing concepts and methods in the context of concurrency between threads or processes?

sobes.tech AI

Answer from AI

In conditions of competition between threads or processes, synchronization of access to shared resources is important to avoid race conditions and ensure data correctness. In Python, various mechanisms are used for this:

  • Lock — a simple mechanism that allows one thread to acquire a resource while others wait.
  • RLock — allows a thread to acquire the same lock multiple times.
  • Semaphore — limits the number of threads that can access a resource simultaneously.
  • Event — used to notify threads about the occurrence of an event.
  • Queue — a thread-safe data structure for exchanging information between threads.

Example of using Lock:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    with lock:
        temp = counter
        temp += 1
        counter = temp

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

print(counter)  # Expected 1000

This approach prevents multiple threads from changing the variable simultaneously, which could lead to errors.

Are you familiar with data processing concepts and… - sobes.tech