在Python中除了可以通過繼承threading.Thread類來實現多線程外,也可以調用thread模組中的start_new_thread()函數來產生新的線程,如下
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)
或者
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中的鎖機制,如下兩段代碼:
代碼一
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
代碼二
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.