Variable-variable variable in a stream

I have a basic question about multithreading in Python: I have a list and I need to change this on a thread. I understand that a list is a mutable type: How do I pass a variable by reference?

But, when I use thread, the list doesn't behave 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 problem?

+3


source to share


1 answer


The code doesn't use threads, but processes that don't use memory.

Use streams:



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

      

+4


source







All Articles