【问题标题】:update python list of lists on multithreaded更新多线程列表的python列表
【发布时间】: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


【解决方案1】:
for i in [[]]*5:
    print(id(i))

输出

139972923894208
139972923894208
139972923894208
139972923894208
139972923894208

所以,如您所见,[[]]*5 不会创建 5 个列表,仅创建一个列表。所有其他 4 个仅代表第一个。 所以当你这样做时

list[0].append(1)

它使列表为

[[1],[1],[1],[1],[1]]

试试

global_list = [[], [], [], [], []]

global_list = [[] for i in range(n_threads)]

【讨论】:

  • 完美运行,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
相关资源
最近更新 更多