Sobes.tech
Junior — Middle

Kuidas saab Pythonis teostada mitme protsessi vahelist suhtlust?

sobes.tech AI

Vastus AI-lt

In Python, the interaction between multiple processes can be organized in several ways:

  1. multiprocessing module — provides tools for creating processes and exchanging data between them. Specifically, there are Queue, Pipe objects for message passing, and Manager for creating shared objects.

  2. Exchange via files or databases — processes can read and write data to shared files or use a database for synchronization and exchange.

  3. Sockets — processes can communicate through network sockets, which is convenient for distributed systems.

  4. System IPC mechanisms — such as semaphores, shared memory, message queues (via posix_ipc or sysv_ipc modules).

Example of using multiprocessing.Queue for message exchange:

from multiprocessing import Process, Queue

def worker(q):
    q.put('Hello from child process')

if __name__ == '__main__':
    q = Queue()
    p = Process(target=worker, args=(q,))
    p.start()
    print(q.get())  # Receives a message from child process
    p.join()