Python's multiprocessing.Pool process global scope problem

拈花ヽ惹草 提交于 2019-12-14 03:07:36

问题


How can I change a global variable STOP to True? As I understand, the problem is with the scope of other processes, but I don't know how to realize it.

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)

回答1:


Use multiprocessing.Value:

...

STOP = Value('b', 0)

...

if x == 19:
    STOP.value = 1

...

while not STOP.value:

...

Unlike multithreading, each process executes in a completely separate environment. New processes copy the state of the current process, but from then on they are independent - like books that come out of the printing press the same, but if you write into one book, the other books of the same title do not get your scribbles. You need the magic that will "share the scribbles" - the magic that is implemented by the various classes of multiprocessing.



来源:https://stackoverflow.com/questions/57353608/pythons-multiprocessing-pool-process-global-scope-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!