python3 Semaphore
同进程的一样
Semaphore管理一个内置的计数器,
每当调用acquire()时内置计数器-1;
调用release() 时内置计数器+1;
计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。
实例:(同时只有5个线程可以获得semaphore,即可以限制最大连接数为5):
from threading import Thread,Semaphore import threading import time def task(): sm.acquire() print(f"{threading.current_thread().name} get sm") time.sleep(3) sm.release() if __name__ == '__main__': sm = Semaphore(5) # 同一时间只有5个线程可以执行。 for i in range(20): t = Thread(target=task) t.start()
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py Thread-1 get sm Thread-2 get sm Thread-4 get sm Thread-5 get sm Thread-3 get sm Thread-6 get sm Thread-7 get sm Thread-9 get sm Thread-10 get sm Thread-8 get sm Thread-11 get sm Thread-13 get sm Thread-12 get sm Thread-14 get sm Thread-15 get sm Thread-16 get sm Thread-17 get sm Thread-19 get sm Thread-20 get sm Thread-18 get sm macname@MacdeMacBook-Pro py %