Search code examples
pythonmultithreadingmultiprocessingpass-by-reference

Pass-by-reference mutable variable in a thread


I have a basic question about multi-threading in Python: I have a list and I need modify this in a thread. I understand that an list is a mutable type: How do I pass a variable by reference?

But, when I using thread the list is not behaving like a mutable type:

from multiprocessing import Process, Lock

def f(l, i, n):
    l.acquire()
    i.append(n)
    l.release()
    print "in:", i

if __name__ == '__main__':
    lock = Lock()

    i = []
    for num in range(10):
        p = Process(target=f, args=(lock, i, num))
        p.start()
        p.join()

    print "out:", i

output

in: [0]
in: [1]
in: [2]
in: [3]
in: [4]
in: [5]
in: [6]
in: [7]
in: [8]
in: [9]
out: []

Can someone please help me with this issue?


Solution

  • The code is not using threads, but processes which does not share memory.

    Use threads:

    from threading import Thread, Lock  # <----
    
    def f(l, i, n):
        l.acquire()
        i.append(n)
        l.release()
        print "in:", i
    
    if __name__ == '__main__':
        lock = Lock()
    
        i = []
        for num in range(10):
            p = Thread(target=f, args=(lock, i, num))  # <----
            p.start()
            p.join()
    
        print "out:", i