1. 线程同步
多个线程争抢同一资源的时候,为了保证资源能够合理的分配给每个线程而避免线程之间争抢资源造成死锁等行为,所以引入了线程同步的机制。
2. 线程同步的机制
2.1 锁机制
锁机制时最常见的线程同步机制,在线程争抢单一少量资源的时候最为常见,订单开发模型中的减库存实例就可以利用锁机制实现,保证数据的合法性。加锁的方式有两种分别为LOCK以及RLOCK
from threading import Lock,RLock
lock = Lock()
lock.acquire() #加锁
lock.release() #释放锁
Lock加锁机制中lock.acquire()
与release()
必须成对出现,否则就会造成 死锁,为了避免死锁造成的影响,引入了RLock机制,保证代码段中必须引入对等数量的lock.acquire()
与release()
,
from threading import Lock,RLock
lock = RLock()
lock.acquire() #加锁
lock.acquire() #加锁
lock.release() #释放锁
lock.release() #释放锁
2.2 条件变量
顾名思义,条件变量实现线程的同步机制就是需要线程满足特定条件之后,线程才可以访问相关资源,通过条件变量实现生产者-消费者模型。
1. 产品模型
class GoodsHandler :
def __init__(self):
self.count = 0
def insertCount(self,count = 1):
self.count += count
def alterCount(self):
self.count -= 1 if self.count > 0 else 0
def isCountZero(self):
return self.count <= 0
2. 生产者模型
class ProducerHandler(threading.Thread) :
def __init__(self,condition,goods,times = 1):
threading.Thread.__init__(self)
self.condition = condition
self.goods = goods
self.times = times
def run(self):
while True :
self.condition.acquire() #锁住资源
self.goods.insertCount()
print("当前为生产者线程: 产品数量:{}".format(self.goods.count))
self.condition.notifyAll() #唤醒所有等待线程
self.condition.release() #释放资源
time.sleep(self.times)
3. 消费者模型
class ConsumerHandler(threading.Thread) :
def __init__(self,condition,goods,times = 2):
threading.Thread.__init__(self)
self.condition = condition
self.goods = goods
self.times = times
def run(self) :
while True :
time.sleep(self.times)
self.condition.acquire()
#无产品,让消费者等待
while self.goods.isCountZero() :
self.condition.wait()
self.goods.alterCount()
print("当前为消费者者线程: 产品数量:{}".format(self.goods.count))
self.condition.release()
2.3 信号量
信号量也提供acquire方法和release方法,每当调用acquire方法的时候,如果内部计数器大于0,则将其减1,如果内部计数器等于0,则会阻塞该线程,直到有线程调用了release方法将内部计数器更新到大于1位置。Semaphore经常用来同步一些有“访客上限”的对象,比如连接池,控制启动线程的数量。
def get_thread_a(semaphore,i):
time.sleep(1)
print("get thread : {}".format(i))
semaphore.release()
def get_thread_b(semaphore):
for i in range(10):
semaphore.acquire()
thread_a = threading.Thread(target=get_thread_a, args=(semaphore,i))
thread_a.start()
if __name__ == "__main__":
semaphore = threading.Semaphore(2)
thread_b = threading.Thread(target=get_thread_b, args=(semaphore,))
thread_b.start()
附:死锁
死锁产生原因:死锁是指两个多个程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。
死锁产生图解:如下图所示,线程A持有资源A,线程B持有资源B,为了保证能够继续推进下去,线程A与B同时拥有资源A与B,但是线程A占有资源资源A,线程A只有申请到资源B才能释放资源A,线程B占有资源B,线程B只有申请到资源A才能释放资源B,线程A,B没有拿到竞争的资源,使得整个推进处于阻塞状态。