• 抢票模拟


    #!/usr/bin/env python
    # encoding: utf-8  
    # Date: 2018/6/17
    import json, time
    from multiprocessing import Process, Lock


    def search(name):
        time.sleep(1)  # 模拟网页延迟
        dic = json.load(open('db.txt', 'r', encoding='utf-8'))
        print('<%s>查看剩余票数(%s)' % (name, dic['count']))


    def get(name):
        time.sleep(1)
        dic = json.load(open('db.txt', 'r', encoding='utf-8'))
        if dic['count'] > 0:
            dic['count'] -= 1
            time.sleep(3)  # 模拟网络写入数据库,还有支付
            json.dump(dic, open('db.txt', 'w', encoding='utf-8'))
            print('<%s> 购票成功' % name)


    def task(name, mutex):
        search(name)  # 查票应该是并发执行
        mutex.acquire()
        get(name)  # 购票应该是串行
        mutex.release()


    if __name__ == '__main__':
        mutex = Lock()  # 互斥锁
        for i in range(10):  # 模拟是个人抢票
            p = Process(target=task, args=('路人%s' % i, mutex))
            p.start()

      #  p.join()  # 会把看都变成串行,代码整体受影响

            
    db.txt
    {"count": 1}       

  • 相关阅读:
    Vue
    linux-----docker
    linux基础
    Flask基础
    websocket
    css
    Mysql数据库基础
    IO多路复用
    线程和协程
    sh_02_del关键字
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9193972.html
Copyright © 2020-2023  润新知