【发布时间】: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