1 import time
2 import threading
3
4 nums=[11,22]
5 def test1(temp):
6 temp.append(33)
7 print("全局的nums是%s" % str(temp))
8
9
10 def test2(temp):
11 print("全局的nums是%s" % str(temp))
12
13
14 def main():
15
16 # args中必须是一个元组,元组中添加一个问号就可以
17 t1=threading.Thread(target=test1,args=(nums,))
18 t2=threading.Thread(target=test2,args=(nums,))
19 t1.start()
20
21 time.sleep(1)
22 t2.start()
23 time.sleep(2)
24 print(nums)
25
26 if __name__ == "__main__":
27 main()
1 import time
2 import threading
3
4 num=0
5 def test1(temp):
6 global num
7 for i in range(temp):
8 num+=1
9 print(num)
10
11
12 def test2(temp):
13 global num
14 for i in range(temp):
15 num+=1
16 print(num)
17
18
19 def main():
20
21 # args中必须是一个元组,元组中添加一个问号就可以
22 t1=threading.Thread(target=test1,args=(100,))
23 t2=threading.Thread(target=test2,args=(100,))
24 t1.start()
25
26 t2.start()
27 time.sleep(2)
28
29 print("全局%d" % num)
30
31 if __name__ == "__main__":
32 main()
1 import time
2 import threading
3
4 num=0
5 def test1(temp):
6 global num
7 for i in range(temp):
8 num+=1
9 print(num)
10
11
12 def test2(temp):
13 global num
14 for i in range(temp):
15 num+=1
16 print(num)
17
18
19 def main():
20
21 # args中必须是一个元组,元组中添加一个问号就可以
22 t1=threading.Thread(target=test1,args=(1000001,))
23 t2=threading.Thread(target=test2,args=(1000000,))
24 t1.start()
25
26 t2.start()
27 time.sleep(2)
28
29 print("全局%d" % num)
30
31 if __name__ == "__main__":
main()
# 创建锁
l=threading.Lock()
# 锁定
l.acquire()
# 解锁
l.release()
1 import time
2 import threading
3 # 默认是没有上锁的
4 lk=threading.Lock()
5 num=0
6 def test1(temp):
7 global num
8 lk.acquire()
9 # 如果之前没有被上锁,则上锁成功,
10 # 如果之前已经被被人上锁了,则阻塞
11 for i in range(temp):
12 num+=1
13 lk.release()
14 print(num)
15
16
17 def test2(temp):
18 global num
19 lk.acquire()
20 # 如果之前没有被上锁,则上锁成功,
21 # 如果之前已经被被人上锁了,则阻塞
22 for i in range(temp):
23 num+=1
24 lk.release()
25 print(num)
26
27
28 def main():
29
30 # args中必须是一个元组,元组中添加一个问号就可以
31 t1=threading.Thread(target=test1,args=(1000001,))
32 t2=threading.Thread(target=test2,args=(1000000,))
33 t1.start()
34
35 t2.start()
36 time.sleep(2)
37
38 print("全局%d" % num)
39
40 if __name__ == "__main__":
41 main()
结果:
1000001
2000001
全局2000001
加锁保证了全举变量不被任意修改
4 lk=threading.Lock()
5 num=0
6 def test1(temp):
7 global num
8 # 如果之前没有被上锁,则上锁成功,
9 # 如果之前已经被被人上锁了,则阻塞
10 for i in range(temp):
11 lk.acquire()
12 num+=1
13 lk.release()
14 print(num)
15
16
17 def test2(temp):
18 global num
19 # 如果之前没有被上锁,则上锁成功,
20 # 如果之前已经被被人上锁了,则阻塞
21 for i in range(temp):
22 lk.acquire()
23 num+=1
24 lk.release()
25 print(num)