设计思路
- 资源池管理:使用列表来模拟数据库连接资源池。
- 线程安全:为了确保多线程环境下对资源池的安全访问,使用
threading.Lock
来进行同步控制。
- 上下文管理器:利用Python的
contextlib.contextmanager
装饰器来实现上下文管理器,这样可以方便地使用with
语句来管理资源的获取和释放。
- 资源耗尽处理:当资源池为空时,线程可以选择等待直到有资源可用,这里通过
threading.Condition
来实现线程的等待和唤醒机制。
Python代码实现
import threading
from contextlib import contextmanager
class ConnectionPool:
def __init__(self, size):
self.pool = [f"Connection-{i}" for i in range(size)]
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
def get_connection(self):
with self.lock:
while not self.pool:
self.condition.wait()
return self.pool.pop()
def return_connection(self, conn):
with self.lock:
self.pool.append(conn)
self.condition.notify()
@contextmanager
def connection_context(pool):
conn = pool.get_connection()
try:
yield conn
finally:
pool.return_connection(conn)
# 示例使用
if __name__ == "__main__":
pool = ConnectionPool(5)
def worker():
with connection_context(pool) as conn:
print(f"{threading.current_thread().name} using {conn}")
threads = []
for _ in range(10):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
for t in threads:
t.join()