1. 程式人生 > 實用技巧 >ElasticSearch-生命週期管理

ElasticSearch-生命週期管理

def search():
    # 查票的函式
    # 開啟檔案,讀出ticket_count
    with open('ticket', 'r', encoding='utf-8') as f:
        dic = json.load(f)
        print('餘票還有:', dic.get('ticket_count'))


def buy():
    with open('ticket', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    time.sleep(random.randint(1, 1))  # 模擬一下網路延遲
    if dic.get('ticket_count') > 0:
        # 能夠買票
        dic['ticket_count'] -= 1
        print('剩餘車票:', dic.get('ticket_count'))
        # 儲存到檔案中去
        with open('ticket', 'w', encoding='utf-8') as f:
            json.dump(dic, f)
            print('買票成功')
    else:
        # 買票失敗
        print('買票失敗,暫無餘票', dic.get('ticket_count'))


# 寫一個函式,先查票,再買票
def task(mutex):
    search()
    # 買票過程要加鎖
    # 買前加鎖
    # mutex.acquire()
    # buy()  # 10個程序變成了序列執行
    # # 買後釋放鎖
    # mutex.release()
    with mutex:
        buy()


if __name__ == '__main__':
    n = int(input('剩餘票數:'))
    with open('ticket', 'w', encoding='utf-8')as f:
        f.write('{"ticket_count": %s}' % n)
    # 鎖的建立,在哪?主程序建立鎖
    mutex = Lock()  # 建立一把鎖
    # 模擬十個人買票(開10個程序)
    for i in range(10):
        t = Process(target=task, args=(mutex,))
        t.start()