码迷,mamicode.com
首页 > 系统相关 > 详细

进程锁(互斥锁)

时间:2020-05-10 12:57:40      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:nbsp   encoding   int   互斥   多次   UNC   lease   基础上   roc   

3:# 抢票示例
import json
import time
from multiprocessing import Process,Lock

def search(i):
    with open(ticket,encoding=utf-8) as f:
        ticket = json.load(f)
    print(%s :当前的余票是%s张%(i,ticket[count]))

def buy_ticket(i):
    with open(ticket,encoding=utf-8) as f:
        ticket = json.load(f)
    if ticket[count]>0:
        ticket[count] -= 1
        print(%s买到票了%i)
    time.sleep(0.1)
    with open(ticket, mode=w,encoding=utf-8) as f:
        json.dump(ticket,f)

def get_ticket(i,lock):
    search(i)
    with lock:   # 代替acquire和release 并且在此基础上做一些异常处理,保证即便一个进程的代码出错退出了,也会归还钥匙
        buy_ticket(i)


if __name__ == __main__:
    lock = Lock()     # 互斥锁
    for i in range(10):
        Process(target=get_ticket,args=(i,lock)).start()


1:# Lock解析
# import time # from multiprocessing import Lock,Process # def func(i,lock): # lock.acquire() # 拿钥匙 # print(‘被锁起来的代码%s‘%i) # lock.release() # 还钥匙 # time.sleep(1) # # if __name__ == ‘__main__‘: # lock = Lock() # for i in range(10): # p = Process(target=func,args=(i,lock)) # p.start() 2:# from multiprocessing import Lock # 互斥锁 不能再同一个进程中连续acquire多次
# lock = Lock() # lock.acquire() # print(1) # lock.release() # lock.acquire() # print(2) # lock.release()

存票文件:

{"count": 0}

 

进程锁(互斥锁)

标签:nbsp   encoding   int   互斥   多次   UNC   lease   基础上   roc   

原文地址:https://www.cnblogs.com/sun-10387834/p/12862802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!