多终端售票(多线程与多进程)

来源:互联网 发布:ubuntu 查看开机启动 编辑:程序博客网 时间:2024/05/10 05:59

售票站大都至少有两个以上的窗口来供应票。每张票上都有一个序号,序号按售出的先后从小到大标号。那么,每个窗口系统在售票时怎么准确的知道下一张即将出售的票号、有无剩余票......这便要引入多线程了。


假设现在有两个窗口,即分别由thread_one和thread_two来控制售票

#test_thread2.py#-*- coding: utf-8 -*-import time,threadingtickts=1000tickt_code=1000lock=threading.Lock()def sales_tick():global tickts,tickt_codetickts=tickts-1tickt_code=tickt_code+1print('Your tickt(%s)! (%s)'%(tickt_code,threading.current_thread().name))def run_thread():while True:      #循环次数够多导致某个线程被中断,从而容易导致tickts被改乱lock.acquire() #因此当某个线程开始执行sales_tick时,给它上一把锁,其它线程不能接近global ticktsif tickts==0:lock.release()   #票销售完breaktry: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,速度都是在毫秒级甚至更短,人无法感知,所以人们会以为这两者是在同时执行,实际上并不是。这种行为术语称为并发











0 0
原创粉丝点击