Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 595
Albert H M Avatar asked Aug 28 '26 09:08

Albert H M


1 Answers

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.

like image 191
ktb Avatar answered Aug 29 '26 23:08

ktb