python 线程锁

 1 """
 2 线程锁
 3 我这用的是python3.7,必须要加锁才可以保证数据的确定性
 4 """
 5 import time
 6 from threading import Thread, Lock
 7 
 8 lock = Lock()
 9 
10 list1 = [0] * 10
11 
12 
13 def task1():
14     lock.acquire()  # 获取锁
15     for i in range(len(list1)):
16         list1[i] = 1
17         print("设置list1")
18         time.sleep(0.5)
19     lock.release()  # 释放锁
20 
21 
22 def task2():
23     lock.acquire()  # 获取锁
24     for i in range(len(list1)):
25         print("list1[i] =", list1[i])
26         time.sleep(0.5)
27     lock.release()  # 释放锁
28 
29 
30 if __name__ == '__main__':
31     t1 = Thread(target=task1, name="task1")
32     t2 = Thread(target=task2, name="task2")
33     t1.start()
34     t2.start()
35 
36     print("over")

 

posted @ 2020-05-31 10:03  乘风去破浪  阅读(189)  评论(0编辑  收藏  举报