Python——threading(執行緒模組)
阿新 • • 發佈:2022-04-12
建立和使用方式基本和程序一致。
有關執行緒的文字講述,請見:計算機——程序&執行緒&協程
import time from threading import Thread,current_thread,enumerate,active_count def func(i1,i2): i = i1+i2 time.sleep(0.5) print(current_thread()) #檢視執行緒的ID並以物件形式顯示,適用於函式使用, for i in range(5): t = Thread(target=func,args=(i,i*2)) #傳值和程序一樣,需要使用元組形式進行傳輸。 t.start() #啟動也是需要使用start print(t.ident) #可以檢視所建立的執行緒ID,可以用在面向物件中使用。 t.daemon = True #建立守護執行緒。 print(enumerate()) #可以看到正在執行的主執行緒和子執行緒。以物件法師呈現在列表當中。 print(active_count()) #可以檢視子執行緒的個數,包括主執行緒。
執行緒+鎖的單例模式
from threading import Thread,Lock class SingLeton(object): instance = None lock = Lock() def __new__(cls, *args, **kwargs): with cls.lock: if not cls.instance: cls.instance = object.__new__(cls) return cls.instance for i in range(10): print(SingLeton())