python-线程中的引用传递可变变量
作者:互联网
我有一个关于Python中多线程的基本问题:我有一个列表,需要在线程中对其进行修改.我了解列表是可变类型:How do I pass a variable by reference?
但是,当我使用线程时,列表的行为不像可变类型:
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
输出
in: [0]
in: [1]
in: [2]
in: [3]
in: [4]
in: [5]
in: [6]
in: [7]
in: [8]
in: [9]
out: []
有人可以帮我解决这个问题吗?
解决方法:
该代码不使用线程,但是不共享内存的进程.
使用线程:
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
标签:multithreading,pass-by-reference,multiprocessing,python 来源: https://codeday.me/bug/20191028/1955730.html