锁机制,信号机制及事件机制
Posted smile568968
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了锁机制,信号机制及事件机制相关的知识,希望对你有一定的参考价值。
在多进程运行处理数据时,会出现争夺资源到时数据混乱的现象,为了避免数据混乱,这里就引入了锁机制:
锁机制:引入Lock模块,l = Lock()在子进程中,l.acquire()表示取到钥匙,锁上门进行数据处理;l.release()表示归还钥匙打开门,让下一个进程进行操作.
信号机制:能够将一把锁配置多把钥匙,能够让多个进程同时进行操作.导入Semaphore模块,sem = Semaphore(n)中的n是int型,表示可以同时进行操作的子程序数.
事件机制:导入Event模块,e.is_set()初始值是False,e.wait()判断is_set()的布尔值,如果是True就实现非阻塞状态,如果是Flaser则是实现阻塞状态(能顾实现一个子进程控制另一个子进程的执行).e.set()将is_set()设为True,e.clear()将其设为False
下面举几个例子说明:
"""12306抢票的例子(Lock)锁机制""" from multiprocessing import Process,Lock import time def check(i): with open("lest")as f: conn = int(f.read()) print("第%s个人查到还剩%s张票" % (i,conn)) def buy_(i,l): l.acquire() with open("lest")as f: conn = int(f.read()) if conn > 0: print("第%s个人买到了票" % i) conn -= 1 else: print("第%s个人没有买到票" % i) time.sleep(0.5) with open("lest","w")as f1: f1.write(str(conn)) f1.close() l.release() if __name__ == ‘__main__‘: l = Lock() for i in range(5): p = Process(target=check,args=(i+1,)) p.start() p1 = Process(target=buy_,args=(i+1,l)) p1.start()
"""红绿灯的例子(事件机制)""" from multiprocessing import Process,Event import time def light(e): while 1: if e.is_set(): time.sleep(3) print("红灯亮") e.clear() else: time.sleep(3) print("绿灯亮") e.set() def car(i,e): e.wait() print("第%s辆车通过" % i) if __name__ == ‘__main__‘: e = Event() light_ = Process(target=light,args=(e,)) light_.start() for i in range(20): time.sleep(0.5) car_ = Process(target=car,args=(i+1,e)) car_.start()
"""小黑屋例子(Semaphore(n)信号机制)""" from multiprocessing import Process,Semaphore import time def func(i,sem): sem.acquire() print("第%s个人来了" % i) time.sleep(3) print("第%s个人又走了" % i) sem.release() if __name__ == ‘__main__‘: sem = Semaphore(3) for i in range(10): p = Process(target=func,args=(i+1,sem)) p.start()
"""存钱取钱的例子(Lock,Value)""" from multiprocessing import Process,Lock,Value def get(num,l,s): l.acquire() num.value -= int(s) l.release() def put(num,l,s1): l.acquire() num.value += int(s1) l.release() if __name__ == ‘__main__‘: num = Value("i",100) s = input("取钱:") s1 = input("存钱:") l = Lock() p = Process(target=get,args=(num,l,int(s))) p.start() p.join() p1 = Process(target=put,args=(num,l,int(s1))) p1.start() p1.join() print(num.value)
以上是关于锁机制,信号机制及事件机制的主要内容,如果未能解决你的问题,请参考以下文章