码迷,mamicode.com
首页 > 编程语言 > 详细

python 线程锁

时间:2020-05-31 11:09:57      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:read   color   target   lease   ==   task   lock   thread   设置   

 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")

 

python 线程锁

标签:read   color   target   lease   ==   task   lock   thread   设置   

原文地址:https://www.cnblogs.com/cfpl/p/12996544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!