Index: trac/db/pool.py
===================================================================
--- trac/db/pool.py	(revision 3747)
+++ trac/db/pool.py	(working copy)
@@ -19,6 +19,7 @@
 except ImportError:
     import dummy_threading as threading
     threading._get_ident = lambda: 0
+import sys
 import time
 
 from trac.db.util import ConnectionWrapper
@@ -38,9 +39,9 @@
         ConnectionWrapper.__init__(self, cnx)
         self._pool = pool
 
-    def close(self):
+    def close(self, thread_exits=False):
         if self.cnx:
-            self._pool._return_cnx(self.cnx)
+            self._pool._return_cnx(self.cnx, thread_exits)
             self.cnx = None
 
     def __del__(self):
@@ -87,20 +88,21 @@
                                                 'connection within %d seconds' \
                                                 % timeout
                     else:
+                        print>>sys.stderr, '[%d] wait for connection...' % tid
                         self._available.wait()
             self._active[tid] = [1, cnx]
             return PooledConnection(self, cnx)
         finally:
             self._available.release()
 
-    def _return_cnx(self, cnx):
+    def _return_cnx(self, cnx, thread_exits=False):
         self._available.acquire()
         try:
             tid = threading._get_ident()
             if tid in self._active:
                 num, cnx_ = self._active.get(tid)
                 assert cnx is cnx_
-                if num > 1:
+                if num > 1 and not thread_exits:
                     self._active[tid][0] = num - 1
                 else:
                     del self._active[tid]
@@ -109,6 +111,7 @@
                         if cnx.poolable:
                             self._dormant.append(cnx)
                         else:
+                            cnx.close()
                             self._cursize -= 1
                         self._available.notify()
         finally:
@@ -118,6 +121,6 @@
         self._available.acquire()
         try:
             for cnx in self._dormant:
-                cnx.cnx.close()
+                cnx.cnx.close() ### should be cnx.close()
         finally:
             self._available.release()
Index: trac/web/main.py
===================================================================
--- trac/web/main.py	(revision 3747)
+++ trac/web/main.py	(working copy)
@@ -357,7 +357,7 @@
                 pass
             return req._response or []
         finally:
-            db.close()
+            db.close(True)
 
     except HTTPException, e:
         env.log.warn(e)

