Sobes.tech
Junior — Middle

How is data exchange and synchronization carried out between different execution threads?

sobes.tech AI

Answer from AI

In Python, data exchange between threads is usually carried out through shared objects, such as queues (queue.Queue), lists, or dictionaries, with synchronization used to prevent race conditions.

Synchronization mechanisms from the threading module are used:

  • Lock — provides exclusive access to a resource.
  • RLock — allows a thread to acquire the lock multiple times.
  • Event — used to notify threads about the occurrence of an event.
  • Condition — for more complex synchronization with waiting for conditions.

Example of using a queue and a lock:

import threading
import queue

q = queue.Queue()

# Producer thread
def producer():
    for i in range(5):
        q.put(i)
        print(f'Produced: {i}')

# Consumer thread
def consumer():
    while True:
        item = q.get()
        if item is None:
            break
        print(f'Consumed: {item}')
        q.task_done()

producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)

producer_thread.start()
consumer_thread.start()

producer_thread.join()
q.put(None)  # signal to end consumer
consumer_thread.join()

Thus, data exchange occurs through thread-safe structures (e.g., queue.Queue), and synchronization is achieved through locks and other primitives from threading.