猿问

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

我试图更加熟悉并发。这样我就可以对一些更复杂的任务进行并行处理。为了学习,我只是尝试在 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)

任何深入了解为什么它在尝试使用进程而不是线程时不起作用?


慕森王
浏览 136回答 1
1回答

绝地无双

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

相关分类

Python
我要回答