【发布时间】:2021-04-30 10:52:13
【问题描述】:
我有这个简单的 python 代码:
from threading import Lock, Condition, Thread
n_threads = 5
global_list = [[]]*n_threads
def update_list(t_id, lock):
global global_list
for i in range(t_id, t_id+4, 1):
lock.acquire()
global_list[t_id].append(i)
lock.release()
print('finishing', t_id)
all_threads = []
l = Lock()
for i in range(n_threads):
c = Thread(name='name %s' % i, target=update_list, args=(i,l,))
all_threads.append(c)
c.start()
for my_thread in all_threads:
my_thread.join()
基本上我要做的是每个线程更新其中一个列表,并且在我的代码末尾,变量 global_list 中的每个列表都将具有来自单个线程的元素,如下所示:
global_list[0] = [0,1,2,3]
global_list[1] = [1,2,3,4]
...
我得到的是:
global_list[0] = [0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
global_list[1] = [0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
...
我正在使用互斥锁来保护操作,所以基本上我不知道为什么它不适用于 python 中的列表以及是否可以使用某些东西来实现这一点。
【问题讨论】:
-
a = [[]]*n_threads创建[[], [], [], [], []]但所有 5 个列表都是相同的,它们是。当你在做global_list[t_id].append(i)时,因为其他 4 个列表是一样的,所以它会复制值。试试copy
标签: python arrays multithreading list mutex