Python用上鎖和解鎖 lock lock.acquire lock.release 模擬搶火車票
阿新 • • 發佈:2019-04-25
range bsp sin multi 上鎖 dump col bing total
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 模擬搶火車票