python多线程之线程同步--锁

 1 '''
 2 线程同步---锁
 3 不同线程操作某一个对象时,容易出现数据不完整或者不一致!
 4 解决方案:加锁。在线程需要独占资源的时候,获取锁;
 5 线程不需要独占资源的时候,释放锁,别的线程可以获取锁;
 6 
 7 锁的目的:确保多个线程不会同时操作同一个资源,确保数据完整性和一致性;
 8 同时,又保证了资源可以在不同线程之间轮转
 9 锁的获取和释放的位置不合适,会引起线程阻塞或者死锁。
10 用到就获取,用完即释放。
11 '''
12 # encoding: utf-8
13 
14 import threading
15 import time
16 
17 a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
18 
19 lock = threading.Lock()
20 
21 
22 class MyThread_Set1(threading.Thread):
23 
24     def __init__(self, thid=None, thname=None, step=0.1):
25         # super().__init__(self)
26         threading.Thread.__init__(self)
27         self.step = step
28         self.thid = thid
29         self.thname = thname
30 
31     def run(self):
32         print('%s开始' % self.thname)
33         lock.acquire()  # 获取锁
34         for i in range(len(a)):
35             a[i] = 1
36             time.sleep(0.1)
37 
38         print(a)
39         lock.release()  # 释放锁
40         print('%s结束' % self.thname)
41 
42 
43 class MyThread_Set2(threading.Thread):
44 
45     def __init__(self, thid=None, thname=None, step=0.1):
46         threading.Thread.__init__(self)  # threading.Thread.__init__(self) 中的thread不要加()
47         self.step = step
48         self.thid = thid
49         self.thname = thname
50 
51     def run(self):
52         print('%s开始' % self.thname)
53         lock.acquire()  # 获取锁
54         for i in range(-1, -len(a)-1, -1):
55             a[i] = 2
56             time.sleep(0.1)
57 
58         print(a)
59         lock.release()  # 释放锁
60         print('%s结束' % self.thname)
61 
62 print("主线程开始")
63 th1 = MyThread_Set1(thname='线程1')
64 th2 = MyThread_Set2(thname='线程2')
65 
66 th2.start()
67 th1.start()
68 
69 th1.join()
70 th2.join()
71 print("主线程结束")
原文地址:https://www.cnblogs.com/annatest/p/13356909.html