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多线程技术的介绍。

评论关闭