售票站大都至少有两个以上的窗口来供应票。每张票上都有一个序号,序号按售出的先后从小到大标号。那么,每个窗口系统在售票时怎么准确的知道下一张即将出售的票号、有无剩余票......这便要引入多线程了。
假设现在有两个窗口,即分别由thread_one和thread_two来控制售票
#test_thread2.py
#-*- coding: utf-8 -*-
import time,threading
tickts=1000
tickt_code=1000
lock=threading.Lock()
def sales_tick():
global tickts,tickt_code
tickts=tickts-1
tickt_code=tickt_code+1
print('Your tickt(%s)! (%s)'%(tickt_code,threading.current_thread().name))
def run_thread():
while True: #循环次数够多导致某个线程被中断,从而容易导致tickts被改乱
lock.acquire() #因此当某个线程开始执行sales_tick时,给它上一把锁,其它线程不能接近
global tickts
if tickts==0:
lock.release() #票销售完
break
try:
sales_tick()
finally:
lock.release()
t1=threading.Thread(target=run_thread,name='thread_one')
t2=threading.Thread(target=run_thread,name='thread_two')
t1.start()
t2.start()
t1.join()
t2.join()
print('No tickt')
输出:
Your tickt(1001)! (thread_one)
Your tickt(1002)! (thread_one)
Your tickt(1003)! (thread_one)
Your tickt(1004)! (thread_one)
......
Your tickt(1035)! (thread_two)
Your tickt(1036)! (thread_two)
Your tickt(1037)! (thread_two)
Your tickt(1038)! (thread_two)
......
......
Your tickt(1201)! (thread_one)
Your tickt(1202)! (thread_one)
Your tickt(1203)! (thread_one)
Your tickt(1204)! (thread_one)
看得出是两个窗口互相交替执行
由于CPU执行速度非常之快,两个线程互相争抢CPU,速度都是在毫秒级甚至更短,人无法感知,所以人们会以为这两者是在同时执行,实际上并不是。这种行为术语称为并发