Python multithreading has a wide range of applications. First, let's look at how to apply it. Let's take a look at the cases in life. I hope you will be inspired. Finally, simulate a Python multi-thread program for bus and subway IC Card Fare payment.
There are 10 card readers. Each card reader deducts a dollar each time and enters the General Ledger. Each card reader is charged 10000000 times a day. 100 original accounts. So the final general account should be 10000100. First, do not use mutex lock to lock and comment out the lock code) to see the consequences.
- 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;
The above is an introduction to the related Python multithreading technology.