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')
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix