跳转至

多进程之进程间通信


使用Queue完成进程间通信

import os
import time
from multiprocessing import Process, Queue


def send_someting(queue: Queue, something):
    print(f'发送消息: {something}, 发送消息的进程id: {os.getpid()}')
    for _ in range(3):
        send_time = time.time()
        print(f'发送时间: {send_time}')
        queue.put((something, send_time))


def receive_something(queue: Queue):
    while not queue.empty():
        something, receive_time = queue.get()
        print(f'接受消息: {something}, 接收时间: {receive_time}, 接收消息的进程id: {os.getpid()}')


def main():
    print(f'主进程开始运行, pid为: {os.getpid()}')

    queue = Queue()

    # 发送消息的进程
    process_send = Process(target=send_someting, args=(queue, 'Hello World'))
    process_send.start()

    # 接收消息的进程
    process_receive = Process(target=receive_something, kwargs={'queue': queue})
    process_receive.start()
    # 使用进程同步阻塞主进程, 等待接收消息的进程成功接收消息
    process_receive.join()

    print('主进程运行完毕')


if __name__ == '__main__':
    main()

输出:

主进程开始运行, pid为: 84824
发送消息: Hello World, 发送消息的进程id: 84826
发送时间: 1659782172.101706
发送时间: 1659782172.101969
发送时间: 1659782172.101996
接受消息: Hello World, 接收时间: 1659782172.101706, 接收消息的进程id: 84827
接受消息: Hello World, 接收时间: 1659782172.101969, 接收消息的进程id: 84827
接受消息: Hello World, 接收时间: 1659782172.101996, 接收消息的进程id: 84827
主进程运行完毕