python中的多執行緒threading之新增執行緒:Thread()
阿新 • • 發佈:2018-11-14
百度百科:多執行緒
多執行緒(英語:multithreading),是指從軟體或者硬體上實現多個執行緒併發執行的技術。具有多執行緒能力的計算機因有硬體支援而能夠在同一時間執行多於一個執行緒,進而提升整體處理效能。具有這種能力的系統包括對稱多處理機、多核心處理器以及晶片級多處理(Chip-level multithreading)或同時多執行緒(Simultaneous multithreading)處理器。 [1] 在一個程式中,這些獨立執行的程式片段叫作“執行緒”(Thread),利用它程式設計的概念就叫作“多執行緒處理(Multithreading)”。具有多執行緒能力的計算機因有硬體支援而能夠在同一時間執行多於一個執行緒(臺灣譯作“執行緒”),進而提升整體處理效能。
python中的多執行緒
多執行緒是加速程式計算的有效方式,Python的多執行緒模組threading上手快速簡單。
首先要匯入多執行緒模組:threading
import threading
獲取已經啟用的執行緒數:
threading.active_count()
檢視所有執行緒資訊:
threading.enumerate()
檢視正在執行的執行緒:
threading.current_thread()
新增執行緒:
threading.Thread()#接收引數target代表這個執行緒要完成的任務,需自行定義
附上簡單新增執行緒的例子:
import threading
def thread_job():#自行定義的任務
print("this is an added thread , number is %s" % threading.current_thread())
def main():
added_thread=threading.Thread(target=thread_job())#target=你要定義的任務
added_thread.start()#定義完了一個執行緒要start一下,不然不會啟動
if __name__ == '__main__':
main()