Python的multiprocessing.Pool处理全局范围问题 [英] Python's multiprocessing.Pool process global scope problem
本文介绍了Python的multiprocessing.Pool处理全局范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将全局变量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)
推荐答案
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处理全局范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文