现在有一个函数需要同时修改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)