1、lock锁
import threadingimport timev = []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()
2、rlock锁
import threadingimport timev = []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()
3、semaphore锁
import timeimport threadinglock = 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()
4、condition锁
import timeimport threadinglock = 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 Truedef 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()"""
5、event锁
import timeimport threadinglock = 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()
6、threadinglocal
import timeimport threadingv = 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()
7、线程池
from concurrent.futures import ThreadPoolExecutorimport timedef task(a1,a2): time.sleep(2) print(a1,a2)# 创建了一个线程池(最多5个线程)pool = ThreadPoolExecutor(5)for i in range(40): # 去线程池中申请一个线程,让线程执行task函数。 pool.submit(task,i,8)
8、生产者消费者模型
import timeimport queueimport threadingq = 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()
9、获取当前线程
threading.current_process()