300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python编写代码购买飞机票_Python 模拟航空公司售票程序

python编写代码购买飞机票_Python 模拟航空公司售票程序

时间:2020-01-26 22:27:13

相关推荐

python编写代码购买飞机票_Python 模拟航空公司售票程序

应用场景:有一个航空公司某一航班要进行机票销售,一个航班的机票库存是有限的,很多渠道都在同时销售机票,怎么保证不重复销售。

实现方式:模拟机票库存 创建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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。