2

I am trying to update the value of a variable which is globally declared, from a python function. And I am feeding this function to a Pool.map() method. But I don't see variable getting updated. Please explain what is happening and what is the fix?

from multiprocessing import Pool
a=0
def fun(num):
    global a
    if num==4:
        a=4

if __name__=='__main__':
    pool=Pool()
    pool.map(fun,[1,2,3,4,5,6])
    pool.close()
    pool.join()
    print(a)

Output=0 Expected output = 4

  • 2
    Check out the section on [sharing state between processes](https://docs.python.org/3.7/library/multiprocessing.html#sharing-state-between-processes) – Brad Solomon Jun 22 '19 at 17:15
  • they are *different processes* so they don't share state. – juanpa.arrivillaga Jun 22 '19 at 17:46
  • `from multiprocessing import Pool, Value a = Value('i', 0) def fun(num): if num == 4: a.value = 4 if __name__ == '__main__': pool = Pool() pool.map(fun, [1, 2, 3, 4, 5, 6]) pool.close() pool.join() print(a.value) ` I'm sorry with the formatting. Hope this helps. – Tarun Kolla Jun 22 '19 at 21:53

0 Answers0