1
2
3
4
5
6 """ Thread-safe pool """
7 import collections
8 import time
9 try:
10 import threading
11 except ImportError:
12 import dummy_threading as threading
13
14 from restkit.pool.base import BasePool
15 from restkit.util import sock
16
18
20 self.keepalive = keepalive
21 self.timeout = timeout
22 self.connections = collections.deque()
23
25 while len(self.connections):
26 conn, expires = self.connections.popleft()
27 if expires >= time.time():
28 return conn
29 return None
30
31 - def put(self, conn):
37
39 while self.connections:
40 conn, expires = self.connections.popleft()
41 sock.close(conn)
42
44
45 - def __init__(self, keepalive=10, timeout=300):
50
51 - def get(self, netloc):
52 self._lock.acquire()
53 try:
54 if netloc not in self._hosts:
55 return
56 host = self._hosts[netloc]
57 conn = host.get()
58 return conn
59 finally:
60 self._lock.release()
61
62 - def put(self, netloc, conn):
63 self._lock.acquire()
64 try:
65 if netloc not in self._hosts:
66 host = Host(self.keepalive, self.timeout)
67 self._hosts[netloc] = host
68 else:
69 host = self._hosts[netloc]
70 host.put(conn)
71 finally:
72 self._lock.release()
73
75 self._lock.acquire()
76 try:
77 if netloc not in self._hosts:
78 return
79 host = self._hosts[netloc]
80 host.clear()
81 finally:
82 self._lock.release()
83
85 self._lock.acquire()
86 try:
87 for netloc, host in self._hosts.items():
88 host.clear()
89 del self._hosts[netloc]
90 finally:
91 self._lock.release()
92