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()