1. 程式人生 > >Python實戰之多執行緒程式設計thread模組

Python實戰之多執行緒程式設計thread模組

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

在Python中除了可以通過繼承threading.Thread類來實現多執行緒外,也可以呼叫thread模組中的start_new_thread()函式來產生新的執行緒,如下

[python]
view plain copy print ?
  1. import time, thread  
  2. def timer():  
  3.     print('hello')  
  4. def test():  
  5.     for i in range(010):  
  6.         thread.start_new_thread(timer, ())  
  7. if __name__=='__main__':  
  8.     test()  
  9.     time.sleep(10)  
import time, threaddef timer(): print('hello')def test(): for i in range(0, 10):  thread.start_new_thread(timer, ())if __name__=='__main__': test() time.sleep(10) 

或者

[python] view plain copy print ?
  1. import time, thread  
  2. def timer(name=None, group=None):  
  3.     print('name: ' + name + ', group: ' + group)  
  4. def test():  
  5.     for i in range(010):  
  6.         thread.start_new_thread(timer, ('thread' + str(i), 'group' + str(i)))  
  7. if __name__=='__main__':  
  8.     test()  
  9.     time.sleep(10)  
import time, threaddef timer(name=None, group=None): print('name: ' + name + ', group: ' + group)def test(): for i in range(0, 10):  thread.start_new_thread(timer, ('thread' + str(i), 'group' + str(i)))if __name__=='__main__': test() time.sleep(10) 

這個是thread.start_new_thread(function,args[,kwargs])函式原型,其中function引數是你將要呼叫的執行緒函式;args是講傳遞給你的執行緒函式的引數,他必須是個tuple型別;而kwargs是可選的引數。執行緒的結束一般依靠執行緒函式的自然結束;也可以線上程函式中呼叫thread.exit(),他丟擲SystemExit exception,達到退出執行緒的目的。

 

下面來看一下thread中的鎖機制,如下兩段程式碼:

程式碼一

[python] view plain copy print ?
  1. import time, thread  
  2. count = 0  
  3. def test():  
  4.     global count  
  5.       
  6.     for i in range(010000):  
  7.         count += 1  
  8.       
  9. for i in range(010):  
  10.     thread.start_new_thread(test, ())  
  11. time.sleep(5)  
  12. print count  
import time, threadcount = 0def test(): global count  for i in range(0, 10000):  count += 1 for i in range(0, 10): thread.start_new_thread(test, ())time.sleep(5)print count 

程式碼二

[python] view plain copy print ?
  1. import time, thread  
  2. count = 0  
  3. lock = thread.allocate_lock()  
  4. def test():  
  5.     global count, lock  
  6.     lock.acquire()  
  7.       
  8.     for i in range(010000):  
  9.         count += 1  
  10.       
  11.     lock.release()  
  12. for i in range(010):  
  13.     thread.start_new_thread(test, ())  
  14. time.sleep(5)  
  15. print count  
import time, threadcount = 0lock = thread.allocate_lock()def test(): global count, lock lock.acquire()  for i in range(0, 10000):  count += 1  lock.release()for i in range(0, 10): thread.start_new_thread(test, ())time.sleep(5)print count 

程式碼一中的值由於沒有使用lock機制,所以是多執行緒同時訪問全域性的count變數,導致最終的count結果不是10000*10,而程式碼二中由於是使用了鎖,從而保證了同一個時間只能有一個執行緒修改count的值,所以最終結果是10000*10.

 

 

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述