1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import time
import json from multiprocessing import Process,Lock
def check(i): with open('ticket', 'rt', encoding='utf-8') as f: res = json.load(f) print('%s:在查询票,票还剩%s张' % (i, res['count'])) if res['count'] > 0: return True
def buy(i): with open('ticket', 'rt', encoding='utf-8') as f: res = json.load(f) time.sleep(1) if res['count'] > 0: print('%s现在要买了,票数还是大于0'%i) res['count'] -= 1 time.sleep(2) with open('ticket', 'wt', encoding='utf-8') as f1: json.dump(res, f1) print('%s这个人购票成功' % i) else: print('%s这个人购票失败,票不够了,买不了了' % i)
def task(i,lock): res = check(i) if res: lock.acquire() buy(i) lock.release()
if __name__ == '__main__': lock=Lock() for i in range(10): p = Process(target=task, args=[i,lock ]) p.start()
|