问题
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