綜述
多線程是程序設計中的一個重要方面,尤其是在服務器Deamon程序方面。無論何種系統,線程調度的開銷都比傳統的進程要快得多。
Python可以方便地支持多線程。可以快速創建線程、互斥鎖、信號量等等元素,支持線程讀寫同步互斥。美中不足的是,Python的運行在Python 虛擬機上,創建的多線程可能是虛擬的線程,需要由Python虛擬機來輪詢調度,這大大降低了Python多線程的可用性。希望高版本的Python可以 解決這個問題,發揮多CPU的最大效率。
網上有些朋友說要獲得真正多CPU的好處,有兩種方法:
1.可以創建多個進程而不是線程,進程數和cpu一樣多。
2.使用Jython 或 IronPython,可以得到真正的多線程。
閑話少說,下面看看Python如何建立線程
Python線程創建
使用threading模塊的 Thread類
類接口如下
啟動這個線程
import time,datetimeimport 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)注意,先不用互斥鎖進行臨界段訪問控制,運行結果如下:
從結果看到,程序確實是多線程運行的。但是由于沒有對對象Account進行互斥訪問,所以結果是錯誤的,只有3434612,比原預計少了很多。
打開鎖后:
這次可以看到,結果正確了。運行時間比不進行互斥多了很多,不過這也是同步的代價。
同時發現,寫多線程,多進程類的程序,不能用自帶的idle來運行。會有錯誤。
|
新聞熱點
疑難解答
圖片精選