我試圖更加熟悉并發。這樣我就可以對一些更復雜的任務進行并行處理。為了學習,我只是嘗試在 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 終端時遇到過這個問題。您定義的函數不適用于每個子進程,因此每個子進程都會立即終止。解決方案是在單獨的文件中定義該函數并導入它,然后嘗試使用該導入的函數進行映射。
添加回答
舉報
0/150
提交
取消