Python多線程如何解決公車收費(fèi)中的問題
作者:佚名
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)行鎖定(注釋掉了鎖定代碼),看看后果如何。
- import time,datetime
- import threading
- def worker(a_tid,a_account):
- global g_mutex
- print "Str " , a_tid, datetime.datetime.now()
- for i in range(1000000):
- #g_mutex.acquire()
- a_account.deposite(1)
- #g_mutex.release()
- print "End " , a_tid , datetime.datetime.now()
- class Account:
- def __init__ (self, a_base ):
- self.m_amount=a_base
- def deposite(self,a_amount):
- self.m_amount+=a_amount
- def withdraw(self,a_amount):
- self.m_amount-=a_amount
- if __name__ == "__main__":
- global g_mutex
- count = 0
- dstart = datetime.datetime.now()
- print "Main Thread Start At: " , dstart
- #init thread_pool
- thread_pool = []
- #init mutex
- g_mutex = threading.Lock()
- # init thread items
- acc = Account(100)
- for i in range(10):
- th = threading.Thread(target=worker,args=(i,acc) ) ;
- thread_pool.append(th)
- # start threads one by one
- for i in range(10):
- thread_pool[i].start()
- #collect all threads
- for i in range(10):
- threading.Thread.join(thread_pool[i])
- dend = datetime.datetime.now()
- print "count=",acc.m_amount
- print "Main Thread End at: " ,dend , " time span " ,
dend-dstart;
上面就是對(duì)相關(guān)Python多線程技術(shù)的介紹。
【編輯推薦】
責(zé)任編輯:張浩
來源:
IT168