【问题标题】:Python's multiprocessing.Pool process global scope problemPython的multiprocessing.Pool进程全局作用域问题
【发布时间】:2019-08-05 07:00:19
【问题描述】:

如何将全局变量 STOP 更改为 True? 据我了解,问题出在其他进程的范围上,但我不知道如何实现。

from multiprocessing import Pool
from time import sleep

STOP = False

def get_nums(state, block_size):
    pages = [i for i in range(state*block_size + 1, (state + 1)*block_size + 1)]
    return pages

def square(x):
    sleep(1)
    if x == 19:
        global STOP
        STOP = True
    print(f'squared\t{x}')
    return x*x

if __name__ == '__main__':
    state = 0
    result = []
    while not STOP:
        with Pool() as p:
            res = p.map(square, get_nums(state, 5))
            result.extend(res)
        print(f'STOP = {STOP}')
        state += 1

    print(result)

【问题讨论】:

  • 您正在使用多处理,因此您已经分离了进程,它们已经分离了STOP 全局变量。你必须使用共享状态:docs.python.org/3/library/…

标签: python multithreading process scope multiprocessing


【解决方案1】:

使用multiprocessing.Value:

...

STOP = Value('b', 0)

...

if x == 19:
    STOP.value = 1

...

while not STOP.value:

...

与多线程不同,每个进程都在完全独立的环境中执行。新进程复制当前进程的状态,但从那时起它们是独立的——就像从印刷机出来的书一样,但是如果你写在一本书上,其他同名的书就不会得到你的涂鸦.您需要能够“分享涂鸦”的魔法——multiprocessing 的各个类实现的魔法。

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多