python 抢购

 创建文件:data.json
内容:{"ticket_num": 1}

import json
import time
from multiprocessing import Process, Lock
def search(user):
    with open('data.json', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    print(f'用户{user}查看余票,还剩{dic.get("ticket_num")}...')


def buy(user):
    with open('data.json', 'r', encoding='utf-8') as f:
        dic = json.load(f)

    time.sleep(0.2)
    if dic['ticket_num'] > 0:
        dic['ticket_num'] -= 1
        with open('data.json', 'w', encoding='utf-8') as f:
            json.dump(dic, f)
        print(f'用户{user}抢票成功!')
        # 加入购物车
        return 1

    else:
        return 0


def run(user, mutex):
    search(user)
    mutex.acquire()  # 加锁
    r = buy(user)
    mutex.release()  # 释放锁
    return r


def rundui(id):
    mutex = Lock()
    return run(id,mutex)
    # for i in range(10):  # 模拟10个用户抢票
    #         p = Process(target=run, args=(f'用户{i}', mutex))
    #         p.start()
t = rundui(3)
if t>0:
    print("ok")

评论

刷新

友情链接