多執行緒—賣票

再也不能沉默發表於2018-11-22
題目:python3多執行緒

 

import threading
import time
list_ticket=[]      #定義票池
lock=threading.Lock() #獲得多執行緒鎖
num=30#票數
for i in range(1,num+1):
     #ticket_num="0"*(len(str(num))-len(str(i)))+str(i)    #001,003,013
     ticket_num=str(i).zfill(3)
     list_ticket.append(ticket_num)
# print(list_ticket)
def seel_ticket(num):  # 通過傳參來用視窗買票
    #全域性變數
   # global list_ticket
   #time.sleep(1)
   while len(list_ticket)>0:
       #time.sleep(0.5)
       lock.acquire()      #開啟執行緒鎖
       print("正在列印票")
       thre = list_ticket[0]   #依次買票
       print(num,"號視窗售票點出票成功,票號為:",thre )
       del list_ticket[0]   #取出以後就得馬上刪除
       lock.release()      #釋放
       time.sleep(0.1)    # 必須有這個睡眠
#++++++===========================================================
# #新建執行緒
# list_thread=[]   # 執行緒的集合
for i in range(5):
    thread = threading.Thread(target=seel_ticket, args=(i+1,)).start()
    # list_thread.append(thread)
# for i in list_thread:
#     i.start()


# #建立5個執行緒
# thread=threading.Thread(target=seel_ticket,args=(1,))
# thread2=threading.Thread(target=seel_ticket,args=(2,))
# thread3=threading.Thread(target=seel_ticket,args=(3,))
# thread4=threading.Thread(target=seel_ticket,args=(4,))
# thread5=threading.Thread(target=seel_ticket,args=(5,))
# #啟動
# thread.start()
# thread2.start()
# thread3.start()
# thread4.start()
# thread5.start()

 

 

 




相關文章