# -*- coding: utf-8 -*- """ 主线程要等到所有非守护线程结束,才能结束。 db.json----->{"count":1} """ import json from threading import Thread, Lock import time def search(name): with open(‘db.json‘, ‘rt‘, encoding=‘utf-8‘) as f: dic = json.load(f) time.sleep(1) count = dic[‘count‘] print(‘%s查看余票为%s‘ % (name, count)) def buy(name): with open(‘db.json‘, ‘rt‘, encoding=‘utf-8‘) as f: dic = json.load(f) if dic[‘count‘] == 0: print(‘%s 余票为0啦‘ % name) return dic[‘count‘] -= 1 with open(‘db.json‘, ‘wt‘, encoding=‘utf-8‘) as w: json.dump(dic, w) time.sleep(1) print(‘%s 购票成功‘ % name) def task(name, mutex): search(name) mutex.acquire() # 添加线程锁 buy(name) mutex.release() # 解除线程锁 if __name__ == ‘__main__‘: mutex = Lock() # 生成一个锁对象 for i in range(1, 5): t = Thread(target=task, args=(‘用户%s‘ % i, mutex)) t.start() # 用户2查看余票为1 # 用户4查看余票为1 # 用户3查看余票为1 # 用户1查看余票为1 # 用户4 购票成功 # 用户2 余票为0啦 # 用户3 余票为0啦 # 用户1 余票为0啦
原文地址:https://www.cnblogs.com/qianzhengkai/p/10827364.html
时间: 2024-11-09 06:23:46