Search code examples
pythonmultiprocessingmutable

Mutable Variable in Multiprocessing


Ok i try to modify value of an array by two different process. I have read the docs about using proxy list, i use it but i didnt know why it doesnt work.

So 1 array and two process modify it in the same time..

import multiprocessing as mp
from multiprocessing.sharedctypes import Value, Array
import time

def decrement(baris):
    for x in range(0,5):
        c = [x-1 for x in baris]
        baris = Array('i', c)
        print(baris[:])
        time.sleep(1)
    print(baris[:])

def assign(baris):
    for x in range(0,2):
        f = baris[:]
        f[1] = 5
        baris = Array('i',f)
        time.sleep(1)
    print(baris[:])


if __name__ == '__main__':
    baris = Array('i',[10,10,10], lock=mp.Lock())
    decrease = mp.Process(target = decrement, args=(baris,))
    decrease.daemon = True
    decrease.start()
    change = mp.Process(target = assign, args=(baris,))
    change.daemon = True
    change.start()

    decrease.join()
    change.join()

    dir(baris)
    print(baris[:])# + 'Final')

baris is the variable that i hope changed in the end. c and f are the proxy list. When the process run, process 'assign' change value of baris[1] to 5 but process 'decrement' didnt mention that change. And in the end, baris didnt change at all!!!! I stuck and didnt know what to do, is that any possible way to run what i desire? In the end i hope i get baris = [5,4,5].

Just correct if my grammar wrong etc.


Solution

  • So I just tested my comment.

    import multiprocessing as mp
    from multiprocessing.sharedctypes import Array
    import time
    
    def decrement(baris):
        for x in range(0,5):
            for i, v in enumerate(baris):
                baris[i] = v - 1
            print(baris[:])
            time.sleep(1)
        print(baris[:])
    
    def assign(baris):
        for x in range(0,2):
            baris[1] = 5
            time.sleep(1)
        print(baris[:])
    
    
    if __name__ == '__main__':
        baris = Array('i',[10,10,10], lock=mp.Lock())
        decrease = mp.Process(target = decrement, args=(baris,))
        decrease.daemon = True
        decrease.start()
        change = mp.Process(target = assign, args=(baris,))
        change.daemon = True
        change.start()
    
        decrease.join()
        change.join()
    
        dir(baris)
        print(baris[:])# + 'Final')
    

    baris is a shared pointer, and when you assign back to it by using the proxy lists, you are simply modifying the local copy of the pointer value being passed. If you want to modify the shared value, you must do assignments directly to the shared value.