为了账号安全,请及时绑定邮箱和手机立即绑定

python并发.futures线程与进程问题

python并发.futures线程与进程问题

慕森王 2023-07-11 17:31:53
我试图更加熟悉并发。这样我就可以对一些更复杂的任务进行并行处理。为了学习,我只是尝试在 python(spyder 解释器)中执行此代码:import concurrent.futuresimport timestart = time.perf_counter()def do_something(seconds):    print(f'Sleeping {seconds} second(s)...')    time.sleep(seconds)    return f'Done Sleeping...{seconds}'if __name__ =='__main__':    with concurrent.futures.ThreadPoolExecutor() as executor:        secs = [5, 4, 3, 2, 1]        results = executor.map(do_something, secs)            # for result in results:        #     print(result)        finish = time.perf_counter()        print(f'Finished in {round(finish-start, 2)} second(s)')我得到了我期望的输出:runfile('D:/untitled1.py', wdir='D:/MarketProject')Sleeping 5 second(s)...Sleeping 4 second(s)...Sleeping 3 second(s)...Sleeping 2 second(s)...Sleeping 1 second(s)...Finished in 5.0 second(s)但是当我将 'concurrent.futures.ThreadPoolExecutor()' 更改为 concurrent.futures.ProcessPoolExecutor() 时,我得到的只是runcell(0, 'D:/untitled1.py')Finished in 0.12 second(s)任何深入了解为什么它在尝试使用进程而不是线程时不起作用?
查看完整描述

1 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

我之前在 Windows 上使用 Jupyter 笔记本和 Python 终端时遇到过这个问题。您定义的函数不适用于每个子进程,因此每个子进程都会立即终止。解决方案是在单独的文件中定义该函数并导入它,然后尝试使用该导入的函数进行映射。



查看完整回答
反对 回复 2023-07-11
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信