標籤:python 多線程
一、簡述
CPython實現細節: 由於GIL(Global Interpreter Lock),在CPython中一次只能有一個線程來執行python代碼,不過有些面向執行的庫可以克服這個限制。如果想要使你的應用程式更好的利用電腦資源的話,最好使用multiprocessing。 但是,如果同時運行多個I/O任務的話,線程依然是一個很好地選擇。
python線程的作用主要是應對I/O任務,例如網路資料的讀寫等。
二、樣本
1. 函數說明。
start_new_thread ( function , args [ , kwargs ] )
建立一個新的線程,返回一個線程標識符。function是線程函數,args是線程函數的參數,是一個list。kwargs選擇性參數,可不填。
#!/usr/bin/env python# _*_ coding = utf-8 _*_import threadimport timedef work_thread(id): cnt = 1 print "Thread %d is runing..." % id while True: print "Thread with ID %d has counter value %d" % (id, cnt) time.sleep(2) cnt += 1for i in range(1,5): thread.start_new_thread(work_thread,(i,))print "Main thread doing an infinite wait loop..."while True: pass
運行代碼,輸出結果如下:
$ ./thread_demo.py
Main thread doing an infinite wait loop…
Thread 3 is runing…
Thread 1 is runing…
Thread 2 is runing…
Thread 4 is runing…
Thread with ID 1 has counter value 1
Thread with ID 4 has counter value 1
Thread with ID 2 has counter value 1
Thread with ID 3 has counter value 1
Thread with ID 2 has counter value 2
Thread with ID 3 has counter value 2
Thread with ID 4 has counter value 2
Thread with ID 1 has counter value 2
Thread with ID 3 has counter value 3
Thread with ID 4 has counter value 3
Thread with ID 1 has counter value 3
Thread with ID 2 has counter value 3
Thread with ID 1 has counter value 4
Thread with ID 4 has counter value 4
Thread with ID 2 has counter value 4
Thread with ID 3 has counter value 4
線程退出函數:
thread.exit ()。結束當前線程。調用該函數會觸發 SystemExit 異常,如果沒有處理該異常,線程將結束。
python 多線程 start_new_thread()