首页 > 编程语言 > 详细

Python用上锁和解锁 lock lock.acquire lock.release 模拟抢火车票

时间:2019-04-24 21:55:07      阅读:316      评论:0      收藏:0      [点我收藏+]

Python用上锁和解锁  lock lock.acquire lock.release 模拟抢火车票

import json
import time
from multiprocessing import Process, Lock

# with open(‘catalogue.json‘, ‘w‘) as fp:
# dic = {‘total‘: 3}
# json.dump(dic, fp)


def check(buyers):
with open(‘catalogue.json‘, mode=‘r‘) as fp:
dic = json.load(fp)
# print(dic,type(dict))
print(‘%s 查询余票:%s‘ % (buyers, dic[‘total‘]))


def buy_tickets(buyers):
with open(‘catalogue.json‘, mode=‘r‘) as fp:
dic = json.load(fp)
time.sleep(0.8)
if dic[‘total‘] > 0:
print(‘%s 买到票了‘ % buyers)
dic[‘total‘] -= 1
with open(‘catalogue.json‘, ‘w‘) as fp:
json.dump(dic, fp)
else:
print(‘%s 没买到这个票‘ % buyers)


def ticket_grabbing(buyers, lock):
check(buyers)
lock.acquire()
buy_tickets(buyers)
lock.release()


if __name__ == ‘__main__‘:
lock = Lock()
for i in range(10):
p = Process(target=ticket_grabbing, args =(‘buyers%s‘ % i, lock))
p.start()

Python用上锁和解锁 lock lock.acquire lock.release 模拟抢火车票

原文:https://www.cnblogs.com/longcaoyu/p/2019lcy.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!