threading多執行緒

2022-06-26 22:12:24 字數 1180 閱讀 7817

什麼是執行緒?

執行緒是作業系統能夠進行運算排程的最小單位。它被包含在程序之中,是程序中的實際運作單位。一條執行緒指的是程序中乙個單一順序的控制流,乙個程序中可以併發多個執行緒,每條執行緒並行執行不同的任務。乙個程序中可以包含多個執行緒。

1

import

threading

2import

time

3 begin =time.time()

4def

f1(a,b):

5print("f1"

,a,b)

6 time.sleep(2)

7def

f2(a,b,c):

8print("f2"

,a,b,c)

9 time.sleep(3)

10 t1 = threading.thread(target=f1,args=(1,1))

11 t2 = threading.thread(target=f2,args=(2,2,2))

12t1.start()

13t2.start()

14 end =time.time()

15print(end-begin)

用過上述的**實現了三條(加上主線程)執行緒的「並行」。

執行緒的建立

t1 = threading.thread(target=f1,args=(1,1)) 其中target是目標函式,無括號。args傳入變數。

t1.start()表示啟用這個執行緒。

.join 和 setdeamon

t1.join必須在start之後加入,表示主線程必須等待該子執行緒執行完之後再結束。

t1.setdaemon(true) 必須在start之前加入。表示主線程不在等待此子執行緒而結束。但是必須等待其他子執行緒結束。

其他內容

執行緒之間資料相互影響,但是程序之間完全獨立。

由於cpython直譯器存在的global interpreter lock使得每個程序一次只能解釋乙個執行緒。所以python沒有實現真正意義上的並行(多核處理同時多個執行緒)。

執行緒分為io密集型和計算密集型。由於gil的存在python在處理多個計算密集型執行緒時比不用多執行緒用時更長。(搶奪cpu資源)在3.5優化後好很多。

解決辦法:1.多個程序(會複製乙個主程序記憶體**)2.協程等。3.其他語言。

多執行緒 threading

python的thread模組是 較底層的模組,python的threading 模組是對thread做了 些包裝的,可以更加 便的被使 1.執行緒執 的封裝 通過上 節,能夠看出,通過使 threading模組能完成多工的程式開 發,為了讓每個執行緒的封裝性更完美,所以使 threading模組時...

python 多執行緒 Threading

簡單的多執行緒 python 2.7 coding utf 8 import threading defrun thread while true cmd input input you choice print cmd if cmd 0 print thread exit break else p...

Python 多執行緒 threading

import threading defthread job print this is a thread of s threading.current thread defmain thread threading.thread target thread job,定義執行緒 thread.sta...