python并发——信号量
信号量通常用于保护数量有限的资源,例如数据库服务器。在资源数量固定的任何情况下,都应该使用有界信号量。在生成任何工作线程前,应该在主线程中初始化信号量。
工作线程生成后,当需要连接服务器时,这些线程将调用信号量的 acquire 和 release 方法:
使用有界信号量能减少这种编程错误:信号量的释放次数多于其请求次数。
from threading import BoundedSemaphore
maxconnections = 5 pool_sema = BoundedSemaphore(value=maxconnections) with pool_sema: conn = connectdb() try: do_some() finally: conn.close()