1
2
3
4
5
6 """
7 Threadsafe Pool class
8 """
9
10 import collections
11 import threading
12
13 from restkit import sock
14
16 """ abstract class from which all connection
17 pool should inherit.
18 """
19
21 """ method used to return a connection from the pool"""
22 raise NotImplementedError
23
25 """ Put an item back into the pool, when done """
26 raise NotImplementedError
27
29 """ method used to release all connections """
30 raise NotImplementedError
31
32
34 """ An host entry """
35
37 object.__init__(self)
38 self._addr = addr
39 self.pool = collections.deque()
40
43 """ Initialize ConnectionPool
44 :attr max_connections: int, the number of maximum connectioons
45 per _host_port
46 """
47 self.max_connections = max_connections
48 self.hosts = {}
49 self._lock = threading.Lock()
50
51
52 - def get(self, address):
53 self._lock.acquire()
54 try:
55 host = self.hosts.get(address)
56 if not host:
57 return None
58
59 if host.pool:
60 return host.pool.popleft()
61
62 return None
63 finally:
64 self._lock.release()
65
66 - def put(self, address, socket):
67 self._lock.acquire()
68 try:
69 host = self.hosts.get(address)
70 if not host:
71 host = _Host(address)
72
73 if len(host.pool) > self.max_connections:
74 sock.close(socket)
75 return
76 host.pool.append(socket)
77 finally:
78 self._lock.release()
79
80 - def clean(self, address):
81 self._lock.acquire()
82 try:
83 host = self.hosts.get(address)
84 if not host: return
85 while host.pool:
86 socket = host.pool.popleft()
87 sock.close(socket)
88 finally:
89 self._lock.release()
90