一、lock鎖安全
import threading import time v = [] lock = threading.Lock() def func(arg): lock.acquire() v.append(arg) time.sleep(0.01) m = v[-1] print(arg,m) lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start()
二、rlock鎖app
import threading import time v = [] lock = threading.RLock() def func(arg): lock.acquire() lock.acquire() v.append(arg) time.sleep(0.01) m = v[-1] print(arg,m) lock.release() lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start()
三、semaphore鎖函數
import time import threading lock = threading.BoundedSemaphore(3) def func(arg): lock.acquire() print(arg) time.sleep(1) lock.release() for i in range(20): t =threading.Thread(target=func,args=(i,)) t.start()
四、condition鎖ui
import time import threading lock = threading.Condition() # ############## 方式一 ############## def func(arg): print('線程進來了') lock.acquire() lock.wait() # 加鎖 print(arg) time.sleep(1) lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() while True: inp = int(input('>>>')) lock.acquire() lock.notify(inp) lock.release() # ############## 方式二 ############## """ def xxxx(): print('來執行函數了') input(">>>") # ct = threading.current_thread() # 獲取當前線程 # ct.getName() return True def func(arg): print('線程進來了') lock.wait_for(xxxx) print(arg) time.sleep(1) for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() """
五、event鎖spa
import time import threading lock = threading.Event() def func(arg): print('線程來了') lock.wait() # 加鎖:紅燈 print(arg) for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() input(">>>>") lock.set() # 綠燈 lock.clear() # 再次變紅燈 for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() input(">>>>") lock.set()
六、threadinglocal線程
import time import threading v = threading.local() def func(arg): # 內部會爲當前線程建立一個空間用於存儲:phone=本身的值 v.phone = arg time.sleep(2) print(v.phone,arg) # 去當前線程本身空間取值 for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start()
七、線程池code
from concurrent.futures import ThreadPoolExecutor import time def task(a1,a2): time.sleep(2) print(a1,a2) # 建立了一個線程池(最多5個線程) pool = ThreadPoolExecutor(5) for i in range(40): # 去線程池中申請一個線程,讓線程執行task函數。 pool.submit(task,i,8)
八、生產者消費者模型blog
import time import queue import threading q = queue.Queue() # 線程安全 def producer(id): """ 生產者 :return: """ while True: time.sleep(2) q.put('包子') print('廚師%s 生產了一個包子' %id ) for i in range(1,4): t = threading.Thread(target=producer,args=(i,)) t.start() def consumer(id): """ 消費者 :return: """ while True: time.sleep(1) v1 = q.get() print('顧客 %s 吃了一個包子' % id) for i in range(1,3): t = threading.Thread(target=consumer,args=(i,)) t.start()
九、獲取當前線程get
threading.current_process()