并发进程加锁代码

import  time,json
from multiprocessing import Process,Lock

def show(i):
    with open("ticket") as f:
        dic = json.load(f)
        print("余票:{}".format(dic["ticket"]))
        time.sleep(0.1)
def buy_ticket(i,lock):
    lock.acquire()
    with open("ticket") as f:
        dic = json.load(f)
        time.sleep(0.1)
    if dic["ticket"] > 0:
        print("{}买到票了".format(i))
        dic["ticket"] -= 1
    else:
        print("{}没有买到票了".format(i))
    with open("ticket","w") as f:
        json.dump(dic,f)
        time.sleep(0.1)
    lock.release()
if __name__ == '__main__':
    for i in range(10):
        p =Process(target=show,args=(i,))
        p.start()
    lock = Lock()
    for i in range(10):
        p =Process(target=buy_ticket,args=(i,lock))
        p.start()

 

posted @ 2018-12-15 13:51  superniao  阅读(319)  评论(0编辑  收藏  举报