应用场景:有一个航空公司某一航班要进行机票销售,一个航班的机票库存是有限的,很多渠道都在同时销售机票,怎么保证不重复销售。
实现方式:模拟机票库存 创建python文件 TicketDB.py
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("第{0}号票,已经售出".format(self.ticket_count))
self.ticket_count -=1
2.实现方式:模拟两个渠道进行售票,采用多线程实现
# -*- 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.总结:
为了保证多个线程间共享库存数据,采用了threading.Lock类,Lock类有两个状态: 锁定 acquire()和 释放 release()