マルチプロセス非同期通信によりプロセスのブロックを回避 キュー、プール apply_asyn

1. Multiprocessing.Queue は非同期通信を実行します。

from multiprocessing import Process, Queue

def process_data(queue):
    while True:
        data = queue.get()  # 从队列中获取数据
        print(data)
        # 处理数据的函数
        # ...

def main():
    # 创建队列
    queue = Queue()

    # 创建进程并启动
    process = Process(target=process_data, args=(queue,))
    process.start()

    while True:
         # 接收数据
        data=22
        # 向队列中放入数据
        queue.put(data)

        # 继续执行其他操作
        # ...

if __name__ == '__main__':
    main()

2. Multiprocessing.Pool apply_asyn は非同期通信を実行します。


from multiprocessing import Pool

def square_number(num):
    return num * num

def main():
    # 创建进程池
    pool = Pool()

    # 要处理的数据
    data = [1, 2, 3, 4, 5]

    # 提交任务到进程池并获取结果
    results = [pool.apply_async(square_number, args=(num,)) for num in data]

    # 等待所有任务完成并获取结果
    processed_data = [result.get() for result in results]

    # 输出处理后的数据
    print(processed_data)

if __name__ == '__main__':
    main()

おすすめ

転載: blog.csdn.net/weixin_42357472/article/details/131718420