小编cgi*_*ini的帖子

Python:在线程之间共享列表

我试图了解线程在同一进程中运行时如何与它们共享的变量空间进行交互的细微差别。以下代码显示了在不同线程中分离的两个函数: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)) …
Run Code Online (Sandbox Code Playgroud)

python multithreading list

3
推荐指数
1
解决办法
9631
查看次数

标签 统计

list ×1

multithreading ×1

python ×1