0

I want to use sharing state with ProcessPoolExecutor

Code:

from multiprocessing import Value
from concurrent.futures import ProcessPoolExecutor

def function(times, a):
    print('I\'m here')
    for _ in range(times):
        with a.get_lock():
            a.value += 1


def main():
    a = Value('I', 0, lock=True)

    with ProcessPoolExecutor(max_workers=5) as executor:
        for i in range(5):
            executor.submit(function, 1000000, a)

    print("----------------------", a.value)


main()

But it stucks and don't even prints 'I'm here'

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27
  • 1
    you may want to try passing your shared variable with an [initializer](https://stackoverflow.com/a/56011074/7540911) – Nullman Feb 20 '20 at 09:13

1 Answers1

0

You need setting shared variable to global, not pass argument.

from multiprocessing import Value
from concurrent.futures import ProcessPoolExecutor

def function(times):
    print('I\'m here')
    for _ in range(times):
        with a.get_lock():
            a.value += 1

def set_global(args):
    global a
    a = args

def main():
    a = Value('I', 0, lock=True)

    set_global(a)
    
    with ProcessPoolExecutor(max_workers=5) as executor:
        for i in range(5):
            executor.submit(function, 1000000)

    print("----------------------", a.value)


if __name__ == '__main__':
    main()
eshizhan
  • 4,235
  • 2
  • 23
  • 23