python多线程实现窗口卖票系统

例一、创建十个线程,卖100张火车票

import threading

list_ticket = []
lock = threading.Lock() # 获取线程锁
num = 100
j = 0

for i in range(1,num+1):
    ticket_num = '0'*(len(str(num))-len(str(i))) + str(i)
    list_ticket.append(ticket_num)

def seel_ticket(k):
    global list_ticket
    global j
    while 1:
        lock.acquire()
        print(k,'号正在打印票')
        if j != 100:
            thre = list_ticket[j]
            j += 1
            print(k,"号出票成功,票号为:", thre)
        else:
            print('票已经卖完')
            break
        lock.release()


list_thread=[]
for i in range(10):
    thread=threading.Thread(target=seel_ticket,args=(i+1,))
    list_thread.append(thread)
for i in list_thread:
    i.start()

例二、
1.多线程/进程卖票系统
设计一个多线程或多进程序来模拟实现一个剧院售票系统:
假设某次演出共有10000张观演券待售,观演券编号分别是2018-12-21-00001,2018-12-21-00002,…到2018-12-21-10000,假设总共有5个售票点同时售票,售票点的编号是1-5,用5个线程或进程模拟这5个售票点的售票情况。
(1)使用多线程或多进程
(2)正确创建观演券的编号
(3)输出每个售票点和其所卖出的观演券的票号
【注意,输出内容必须包含类似“xx号售票点卖出编号为xxx的观演券”的信息,否则本项不得分。】
(4)合理利用锁机制,以保证出票正常;
(5)各售票点不能售出相同票号的观演券

import threading
lock = threading.Lock()
import time
tickets = []
j = 0
for i in range(1,10001):
    a = str(i)
    a = a.rjust(5,'0')
    a = '2018-12-21-' + a
    tickets.append(a)
print(tickets)

def sale(num):
    global tickets
    global j
    while 1:
        print(num,'号售票点正在售票')
        lock.acquire()
        if j != 10000:
            a = tickets[j]
            j += 1
            print(num,'号售票卖出编号为',a,'的观影卷')
        else:
            print('票已经售完')
            break
        lock.release()

list_thread = []
for i in range(1,6):
    a = threading.Thread(target=sale,args=(i,))
    list_thread.append(a)
for k in list_thread:
    k.start()

你可能感兴趣的:(Python代码)