Sobes.tech
Junior — Middle

How is interaction and information exchange between parallel components or threads in a system carried out?

sobes.tech AI

Answer from AI

Interaction and information exchange between parallel components or threads in a system can be carried out in the following ways:

  • Shared memory: threads can read and write data to shared variables or data structures. Synchronization mechanisms (mutexes, semaphores) are used to prevent conflicts.

  • Message queues: components exchange messages through queues, which simplifies communication and reduces coupling.

  • Events and signals: one thread can notify another about the occurrence of a specific event.

  • Pipes and sockets: used for data exchange between processes, including on different machines.

Example of using a queue in Python with the queue module for data exchange between threads:

import threading
import queue

q = queue.Queue()

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

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

threading.Thread(target=producer).start()
threading.Thread(target=consumer).start()

This approach allows safe data exchange between threads.