池.map()无法识别在主线程中声明的变量

2024-04-26 00:50:37 发布

您现在位置:Python中文网/ 问答频道 /正文

比如说:

import multiprocessing

def process(lines):
    print(something)

if __name__ == '__main__':
    something = 'something'
    pool = multiprocessing.Pool(10)
    with open(r'C:\Users\a\testfiles\test.txt') as lines:
            pool.map(process, lines)

我得到一个NameError:名称'something'没有定义。你知道吗

有人知道为什么会这样,知道解决办法吗?你知道吗


Tags: nameimportifmaindefwithopenmultiprocessing
1条回答
网友
1楼 · 发布于 2024-04-26 00:50:37

multiprocessing.Pool不是线程池,而是进程池。Windows不支持分叉,因此必须显式地将something传递给新进程。你知道吗

如果要使用线程池,请改用from multiprocessing.dummy import Pool。你知道吗

相关问题 更多 >