Python實戰之多執行緒程式設計thread模組
阿新 • • 發佈:2018-11-16
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
在Python中除了可以通過繼承threading.Thread類來實現多執行緒外,也可以呼叫thread模組中的start_new_thread()函式來產生新的執行緒,如下
[python]- import time, thread
- def 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 ?- import time, thread
- def 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 ?- import time, thread
- count = 0
- def 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 ?- import time, thread
- count = 0
- lock = 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.