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

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


假设现在有两个窗口,即分别由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,速度都是在毫秒级甚至更短,人无法感知,所以人们会以为这两者是在同时执行,实际上并不是。这种行为术语称为并发











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值