python 多进程+超时机制+进程函数返回值

 

实现多进程,以及拿到每个进程return的返回值,并增加超时机制,如果进程超时,则立即kill

 

复制代码
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import Process, Manager

def target_function(param):
    print(f"Processing parameter: {param} (PID: {os.getpid()})")
    time.sleep(param)
    return f"Process {param} finished"

def run_process_with_timeout(param, timeout, return_dict):
    def target_wrapper():
        return_dict[param] = target_function(param)
    
    p = Process(target=target_wrapper)
    p.start()
    p.join(timeout)
    if p.is_alive():
        p.terminate()  # Terminate the process if it exceeds timeout
        p.join()
        return False
    return True

if __name__ == "__main__":
    params = [2, 6, 3, 100]
    timeout = 5
    start = time.time()
    
    manager = Manager()
    return_dict = manager.dict()
    
    with ProcessPoolExecutor() as executor:
        futures = {executor.submit(run_process_with_timeout, param, timeout, return_dict): param for param in params}

        try:
            for future in as_completed(futures):
                param = futures[future]
                if future.result():
                    result = return_dict[param]
                    print(result)
                else:
                    print(f"Process {param} timed out")
        except Exception as e:
            print("An error occurred:", e)

    end = time.time()
    print(f"Time elapsed: {end - start:.2f} seconds")
    print("All processes have been completed.")
    print('hello')
    print('world')
    print('hello world')
复制代码

 

posted @   WTSRUVF  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示