简体   繁体   English

Python的multiprocessing.Pool处理全局范围问题

[英]Python's multiprocessing.Pool process global scope problem

How can I change a global variable STOP to True ? 如何将全局变量STOP更改为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)

Use multiprocessing.Value : 使用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 . 您需要能够“共享涂鸦”的魔力-由各种类型的multiprocessing实现的魔力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM