多终端售票(多线程与多进程)
2016-09-25 17:15
169 查看
售票站大都至少有两个以上的窗口来供应票。每张票上都有一个序号,序号按售出的先后从小到大标号。那么,每个窗口系统在售票时怎么准确的知道下一张即将出售的票号、有无剩余票......这便要引入多线程了。
假设现在有两个窗口,即分别由thread_one和thread_two来控制售票
输出:
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,速度都是在毫秒级甚至更短,人无法感知,所以人们会以为这两者是在同时执行,实际上并不是。这种行为术语称为并发
假设现在有两个窗口,即分别由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,速度都是在毫秒级甚至更短,人无法感知,所以人们会以为这两者是在同时执行,实际上并不是。这种行为术语称为并发
相关文章推荐
- 多线程 or 多进程
- 运用多线程知识写一个火车站售票系统
- gdb调试多进程和多线程命令
- Python多线程与多进程
- Python多线程与多进程
- 多线程和多进程【转】
- Python之多进程多线程
- LoadRunner中的多进程和多线程
- 多线程和多进程之间的区别
- 多进程和多线程的应用场景
- 用java多线程操作模拟售票系统
- 多线程 or 多进程 (转强力推荐)
- 编程思想之多线程与多进程(1)——以操作系统的角度述说线程与进程
- python【第九篇】多线程、多进程
- gdb调试多进程和多线程命令
- python并发编程之多进程、多线程、异步和协程
- 多线程、多进程TCP服务器、进程池和线程池
- 关于多进程与多线程
- 多线程的基本应--售票系统
- GDB调试信号、多线程、多进程