- Application scenario: an airline needs to sell tickets for a certain flight. The ticket inventory of a flight is limited, and many channels are selling tickets at the same time. How to ensure that there is no repeat sales.
- Implementation method: create python file TicketDB.py by simulating ticket inventory
import threading import time class TicketDB: def __init__(self): self.ticket_count = 5 def get_ticket_count(self): return self.ticket_count def sell_ticket(self): time.sleep(1) print("The first{0}Ticket No. has been sold".format(self.ticket_count)) self.ticket_count -=1
2. Implementation mode: simulate two channels to sell tickets, and adopt multi-threaded implementation
# -*- coding: utf-8 -*- import threading import time from TicketDB import TicketDB db= TicketDB() # create lock lock = threading.Lock() def thread1_body(): global db,lock while True: lock.acquire() current_ticket_count= db.get_ticket_count() if current_ticket_count >0: db.sell_ticket() lock.release() else: lock.release() break time.sleep(1) def thread2_body(): global db,lock while True: lock.acquire() current_ticket_count= db.get_ticket_count() if current_ticket_count >0: db.sell_ticket() lock.release() else: lock.release() break time.sleep(1) def main(): t1= threading.Thread(target=thread1_body) t1.start() t2= threading.Thread(target=thread2_body) t2.start() if __name__=='__main__': main()
3. summary:
In order to share inventory data among multiple threads, the threading.Lock class is used. The Lock class has two states: Lock acquire() and release()