我试图更加熟悉并发。这样我就可以对一些更复杂的任务进行并行处理。为了学习,我只是尝试在 python(spyder 解释器)中执行此代码:
import concurrent.futures
import time
start = 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)
任何深入了解为什么它在尝试使用进程而不是线程时不起作用?
绝地无双
相关分类