Python多线程如何解决公车收费中的问题

开发 后端
Python多线程是目前经常使用的,在不断的发展中我们需要不断的学习。下面我们就来学习下Python语言中的相关技术问题。

Python多线程有很广泛的应用空间,首先我们来看看如何进行相关的应用。下面我们就来看看在生活中的案例。希望大家有些启发。最后,模拟一个公交地铁IC卡缴车费的Python多线程程序。

有10个读卡器,每个读卡器收费器每次扣除用户一块钱进入总账中,每读卡器每天一共被刷10000000次。账户原有100块。所以最后的总账应该为10000100。先不使用互斥锁来进行锁定(注释掉了锁定代码),看看后果如何。

 

  1. import time,datetime  
  2. import threading  
  3. def worker(a_tid,a_account):  
  4. global g_mutex  
  5. print "Str " , a_tid, datetime.datetime.now()  
  6. for i in range(1000000):  
  7. #g_mutex.acquire()  
  8. a_account.deposite(1)  
  9. #g_mutex.release()  
  10. print "End " , a_tid , datetime.datetime.now()  
  11. class Account:  
  12. def __init__ (self, a_base ):  
  13. self.m_amount=a_base 
  14. def deposite(self,a_amount):  
  15. self.m_amount+=a_amount  
  16. def withdraw(self,a_amount):  
  17. self.m_amount-=a_amount 
  18. if __name__ == "__main__":  
  19. global g_mutex  
  20. count = 0 
  21. dstart = datetime.datetime.now()  
  22. print "Main Thread Start At: " , dstart  
  23. #init thread_pool  
  24. thread_pool = []  
  25. #init mutex  
  26. g_mutex = threading.Lock()  
  27. # init thread items  
  28. acc = Account(100)  
  29. for i in range(10):  
  30. th = threading.Thread(target=worker,args=(i,acc) ) ;  
  31. thread_pool.append(th)  
  32. # start threads one by one  
  33. for i in range(10):  
  34. thread_pool[i].start()  
  35. #collect all threads  
  36. for i in range(10):  
  37. threading.Thread.join(thread_pool[i])  
  38. dend = datetime.datetime.now()  
  39. print "count=",acc.m_amount  
  40. print "Main Thread End at: " ,dend , " time span " , 
    dend-dstart; 

上面就是对相关Python多线程技术的介绍。

【编辑推荐】

  1. Python匹配如何才能完成匹配细节
  2. Python正则表达式十种相关的匹配方法
  3. Python字符串替换如何才能进行字符的拆分
  4. 对Python函数的局部变量的介绍
  5. Python编程语言具有相当高的适应能力
责任编辑:张浩 来源: IT168
相关推荐

2010-03-15 18:11:38

Java多线程

2021-10-20 20:27:55

MySQL死锁并发

2017-09-23 22:07:24

深度学习N 体问题GAN

2017-09-28 10:40:10

深度学习多体问题多代理系统

2012-09-05 11:09:15

SELinux操作系统

2019-11-05 14:00:23

Windows 10Outlook附件

2017-10-17 09:21:06

2010-02-01 17:25:09

Python多线程

2010-03-16 17:00:02

Java多线程支持

2018-01-03 08:42:40

Linux命令磁盘空间

2010-04-29 17:46:31

Oracle死锁

2023-03-02 08:19:43

不加锁程序实时性

2019-11-26 14:30:20

Spring循环依赖Java

2023-07-18 16:05:00

IP地址

2009-09-21 17:10:14

struts Hibe

2019-08-15 07:43:38

TCP网络协议丢包

2010-08-31 13:56:38

PHP5多线程

2013-08-16 10:04:46

OpenSUSE 12VirtualBox

2013-12-16 11:01:08

OpenSUSEOpenSUSE 12VirtualBox

2017-06-16 22:14:45

机器学习数据不平衡
点赞
收藏

51CTO技术栈公众号