问题描述
如何将全局变量STOP
更改为True
?据我了解,问题在于其他流程的范围,但我不知道如何实现.
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)
推荐答案
...
STOP = Value('b', 0)
...
if x == 19:
STOP.value = 1
...
while not STOP.value:
...
与多线程不同,每个进程在完全独立的环境中执行.新流程会复制当前流程的状态,但是从那时起,它们是独立的-就像印刷机出版的书籍一样,但是如果您写成一本书,则其他同名书籍则不会乱涂乱画.您需要一种可以共享涂鸦"的魔法-由multiprocessing
的各个类实现的魔法.
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
.
这篇关于Python的multiprocessing.Pool处理全局范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!