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:
-
multiprocessingmodule — provides tools for creating processes and exchanging data between them. Specifically, there areQueue,Pipeobjects for message passing, andManagerfor creating shared objects. -
Exchange via files or databases — processes can read and write data to shared files or use a database for synchronization and exchange.
-
Sockets — processes can communicate through network sockets, which is convenient for distributed systems.
-
System IPC mechanisms — such as semaphores, shared memory, message queues (via
posix_ipcorsysv_ipcmodules).
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()