Python的互斥锁与信号量详解
并发与锁
多个线程共享数据的时候,如果数据不进行保护,那么可能出现数据不一致现象,使用锁,信号量、条件锁
互斥锁
1.互斥锁,是使用一把锁把代码保护起来,以牺牲性能换取代码的安全性,那么Rlock后必须要relase解锁不然将会失去多线程程序的优势
2.互斥锁的基本使用规则:
importthreading #声明互斥锁 lock=threading.Rlock(); defhandle(sid):#功能实现代码 lock.acquire()#加锁 #writercodeing lock.relase()#释放锁
信号量:
1.调用relarse()信号量会+1调用acquire()信号量会-1
可以理解为对于临界资源的使用,以及进入临界区的判断条件
2.semphore():当调用relarse()函数的时候单纯+1不会检查信号量的上限情况。初始参数为0
3.boudedsemphore():边界信号量当调用relarse()会+1,并且会检查信号量的上限情况。不允许超过上限
使用budedsemaphore时候不允许设置初始为0,将会抛出异常
至少设置为1,如consumerproduct时候应该在外设置一个变量,启动时候对变量做判断,决定使不使用acquier
4.信号量的基本使用代码:
#声明信号量: sema=threading.Semaphore(0);#无上限检查 sema=threading.BuderedSeamphore(1)#有上限检查设置 5 apple=1 defconsumner(): seam.acquire();#‐1 9 ifapple==1: pass else:sema2.release();#+1 defproduct(): seam.relarse();#+1 ifapple==1: pass else: print("消费:",apple);
全部的代码:
#-*-coding:utf-8-*- """ CreatedonMonSep921:49:302019 @author:DGW-PC """ #信号量解决生产者消费者问题 importrandom; importthreading; importtime; #声明信号量 sema=threading.Semaphore(0);#必须写参数0表示可以使用数 sema2=threading.BoundedSemaphore(1); apple=1; defproduct():#生产者 globalapple; apple=random.randint(1,100); time.sleep(3); print("生成苹果:",apple); #sema2.release();#+1 ifapple==1: pass else:sema2.release();#+1 defconsumer(): print("等待"); sema2.acquire();#-1 ifapple==1: pass else: print("消费:",apple); threads=[]; foriinrange(1,3): t1=threading.Thread(target=consumer); t2=threading.Thread(target=product); t1.start(); t2.start(); threads.append(t1); threads.append(t2); forxinthreads: x.join();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。