009 模拟一个简单抢票小程序代码

from  multiprocessing import Process
import json,time,os
def search():
    time.sleep(1) # 模拟网络io
    with open('db.txt',mode='rt',encoding='utf-8') as f:
        res = json.load(f)
        print(f'还剩{res["count"]}')
def get():
    with open('db.txt',mode='rt',encoding='utf-8') as f:
        res = json.load(f)
        # print(f'还剩{res["count"]}')
    time.sleep(1) # 模拟网络io
    if res['count'] > 0:
        res['count'] -= 1
        with open('db.txt',mode='wt',encoding='utf-8') as f:
            json.dump(res,f)
            time.sleep(1.5) # 模拟网络io
            print(f'进程{os.getpid()} 抢票成功')
    else:
        print('票已经售空啦!!!!!!!!!!!')
def task():
    search()
    get()
if __name__ == '__main__':
    for i in range(15):
        p = Process(target=task)
        p.start()
        p.join()


# 为了保证数据的安全,要牺牲掉效率.
原文地址:https://www.cnblogs.com/abdm-989/p/11512935.html