简单的简单

现在有一个函数需要同时修改2个列表list且他们要保持相同长度,列表中的数据计算是CPU计算密集型,然后有很多个访问程序去读取这两个列表的值

import threading

# 创建锁对象

lock = threading.Lock()

# 全局变量

global_list1 = []

global_list2 = []

def modify_global_lists():

    global global_list1, global_list2

    # 获取锁

    lock.acquire()

    try:

        # 假设我们同时对两个列表进行相同的操作,保持它们的长度一致

        new_elements = [i for i in range(10)]  # 生成一些新元素

        global_list1.extend(new_elements)

        global_list2.extend(new_elements)

    finally:

        # 释放锁

        lock.release()

def read_global_lists():

    global global_list1, global_list2

    # 这里不需要加锁,因为我们只是读取

    print(global_list1, global_list2)

# 创建一个修改全局变量的线程

t1 = threading.Thread(target=modify_global_lists)

threads.append(t1)

t1.start()

# 创建线程

threads = []

# 创建多个读取全局变量的线程

for _ in range(5):

    t = threading.Thread(target=read_global_lists)

    threads.append(t)

    t.start()

# 等待所有线程完成

for t in threads:

    t.join()

print("Final value of global_list1:", global_list1)

print("Final value of global_list2:", global_list2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值