Python:在线程之间共享列表

cgi*_*ini 3 python multithreading list

我试图了解线程在同一进程中运行时如何与它们共享的变量空间进行交互的细微差别。以下代码显示了在不同线程中分离的两个函数:prod 和 consum。这两个函数被赋予相同的列表和锁参数:它们使用 da_list 来共享数据,并使用 lockguy 来同步/线程安全共享。

我的主要问题是:当我运行这段代码时,它打印出 (1, 0, 0, 0, 0 ...) 而不是 (1,2,3,4,5,6 ...) 我期待。当我删除 consum 函数中的 l =[0] 行时,我得到了预期的行为。为什么 l = [0] 搞砸了?当消耗完成时,da_list应该是[0]。随后调用 prod 应将 da_list 重置为 [da_int]。谢谢您的帮助。

import threading
import time

    def prod(l,lock):
        da_int = 0
        while True:
            with lock:
                time.sleep(0.1)
                da_int += 1
                l[0] = da_int

    def consum(l,lock):

        data = ''

        while True:
            with lock:
                time.sleep(0.1)
                print(l[0])
                l = [0]

    def main():

        da_list = [0]
        lockguy = threading.Lock()


        thread1 = threading.Thread(target = prod, args=(da_list,lockguy))
        thread2 = threading.Thread(target = consum, args=(da_list,lockguy))
        thread1.daemon = True
        thread2.daemon = True
        thread1.start()
        thread2.start()

        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            print('done')




    if __name__ == '__main__':
        main()
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 5

l = [0]
Run Code Online (Sandbox Code Playgroud)

您似乎对 Python 中的赋值工作方式感到困惑。l您似乎认为上面的行修改了先前绑定的对象。它不是。

上面的行创建一个新列表并将本地名称绑定l到它。l先前绑定的任何对象都不再与该名称相关l。在此范围内的任何后续使用都l将引用此新创建的列表。

考虑这个单线程代码:

a = b = [1]  # a and b are both bound to the same list
print a,b    # [1] [1]
b[0] = 2     # modifies the object to which a and b are bound
print a,b    # [2] [2]
b = [0]      # now b is bound to a new list
print a,b    # [2] [0]
Run Code Online (Sandbox Code Playgroud)

注意如何b[0] = 2b = [0]不同。在第一个中,绑定的对象b被修改。在第二个中,b绑定到一个全新的对象。

同样,l = [0]在您的代码绑定l到新对象时,您已经丢失并且无法重新获得对原始对象的任何引用。