自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python多線程如何解決公車收費(fèi)中的問題

開發(fā) 后端
Python多線程是目前經(jīng)常使用的,在不斷的發(fā)展中我們需要不斷的學(xué)習(xí)。下面我們就來學(xué)習(xí)下Python語(yǔ)言中的相關(guān)技術(shù)問題。

Python多線程有很廣泛的應(yīng)用空間,首先我們來看看如何進(jìn)行相關(guān)的應(yīng)用。下面我們就來看看在生活中的案例。希望大家有些啟發(fā)。最后,模擬一個(gè)公交地鐵IC卡繳車費(fèi)的Python多線程程序。

有10個(gè)讀卡器,每個(gè)讀卡器收費(fèi)器每次扣除用戶一塊錢進(jìn)入總賬中,每讀卡器每天一共被刷10000000次。賬戶原有100塊。所以最后的總賬應(yīng)該為10000100。先不使用互斥鎖來進(jìn)行鎖定(注釋掉了鎖定代碼),看看后果如何。

 

  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; 

上面就是對(duì)相關(guān)Python多線程技術(shù)的介紹。

【編輯推薦】

  1. Python匹配如何才能完成匹配細(xì)節(jié)
  2. Python正則表達(dá)式十種相關(guān)的匹配方法
  3. Python字符串替換如何才能進(jìn)行字符的拆分
  4. 對(duì)Python函數(shù)的局部變量的介紹
  5. Python編程語(yǔ)言具有相當(dāng)高的適應(yīng)能力
責(zé)任編輯:張浩 來源: IT168
相關(guān)推薦

2010-03-15 18:11:38

Java多線程

2017-09-28 10:40:10

深度學(xué)習(xí)多體問題多代理系統(tǒng)

2017-09-23 22:07:24

深度學(xué)習(xí)N 體問題GAN

2012-09-05 11:09:15

SELinux操作系統(tǒng)

2021-10-20 20:27:55

MySQL死鎖并發(fā)

2019-11-05 14:00:23

Windows 10Outlook附件

2017-10-17 09:21:06

2010-03-16 17:00:02

Java多線程支持

2010-02-01 17:25:09

Python多線程

2018-01-03 08:42:40

Linux命令磁盤空間

2023-03-02 08:19:43

不加鎖程序實(shí)時(shí)性

2019-11-26 14:30:20

Spring循環(huán)依賴Java

2024-12-05 09:06:58

2023-07-18 16:05:00

IP地址

2010-08-31 13:56:38

PHP5多線程

2019-08-15 07:43:38

TCP網(wǎng)絡(luò)協(xié)議丟包

2024-11-19 17:54:15

JavaCASABA問題

2017-06-16 22:14:45

機(jī)器學(xué)習(xí)數(shù)據(jù)不平衡

2020-07-08 07:00:00

LinuxCPU應(yīng)用程序

2023-10-30 18:35:47

MySQL主從延時(shí)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)