一 信号量
信号量也是一把锁,可以指定信号量为5,对比互斥锁同一时间只能有一个任务抢到锁去执行,信号量同一时间可以有5个任务拿到锁去执行,如果说互斥锁是合租房一个们,每次只能出去一个人,那么信号量就相当于一群路人去争取合租房的多个们出去,合租房有多少个门,这意味着同一时间可以有多个人出去,但合租房的出去的门是一定的,这们多少是信号量。
from threading import Thread,Semaphore import threading import time def func(): sm.acquire() print('%s get sm' %threading.current_thread().getName()) time.sleep(3) sm.release() if __name__ == '__main__': sm=Semaphore(5) #定义信号量大小,同时有5人抢占 for i in range(23): t=Thread(target=func) t.start()
Thread-1 get sm Thread-2 get sm Thread-3 get sm Thread-4 get sm Thread-5 get sm Thread-6 get sm Thread-7 get sm Thread-8 get sm Thread-9 get sm Thread-10 get sm Thread-11 get sm Thread-12 get sm Thread-13 get sm Thread-14 get sm Thread-15 get sm Thread-16 get sm Thread-17 get sm Thread-18 get sm Thread-19 get sm Thread-20 get sm Thread-22 get sm Thread-23 get sm Thread-21 get sm