@@ -284,8 +284,7 @@ def connection(self, shareable=True):
284284 then the connection may be shared with other threads.
285285 """
286286 if shareable and self ._maxshared :
287- self ._lock .acquire ()
288- try :
287+ with self ._lock :
289288 while (not self ._shared_cache and self ._maxconnections
290289 and self ._connections >= self ._maxconnections ):
291290 self ._wait_lock ()
@@ -313,12 +312,9 @@ def connection(self, shareable=True):
313312 # put the connection (back) into the shared cache
314313 self ._shared_cache .append (con )
315314 self ._lock .notify ()
316- finally :
317- self ._lock .release ()
318315 con = PooledSharedDBConnection (self , con )
319316 else : # try to get a dedicated connection
320- self ._lock .acquire ()
321- try :
317+ with self ._lock :
322318 while (self ._maxconnections
323319 and self ._connections >= self ._maxconnections ):
324320 self ._wait_lock ()
@@ -331,8 +327,6 @@ def connection(self, shareable=True):
331327 con ._ping_check () # check connection
332328 con = PooledDedicatedDBConnection (self , con )
333329 self ._connections += 1
334- finally :
335- self ._lock .release ()
336330 return con
337331
338332 def dedicated_connection (self ):
@@ -341,24 +335,20 @@ def dedicated_connection(self):
341335
342336 def unshare (self , con ):
343337 """Decrease the share of a connection in the shared cache."""
344- self ._lock .acquire ()
345- try :
338+ with self ._lock :
346339 con .unshare ()
347340 shared = con .shared
348341 if not shared : # connection is idle,
349342 try : # so try to remove it
350343 self ._shared_cache .remove (con ) # from shared cache
351344 except ValueError :
352345 pass # pool has already been closed
353- finally :
354- self ._lock .release ()
355346 if not shared : # connection has become idle,
356347 self .cache (con .con ) # so add it to the idle cache
357348
358349 def cache (self , con ):
359350 """Put a dedicated connection back into the idle cache."""
360- self ._lock .acquire ()
361- try :
351+ with self ._lock :
362352 if not self ._maxcached or len (self ._idle_cache ) < self ._maxcached :
363353 con ._reset (force = self ._reset ) # rollback possible transaction
364354 # the idle cache is not full, so put it there
@@ -367,13 +357,10 @@ def cache(self, con):
367357 con .close () # then close the connection
368358 self ._connections -= 1
369359 self ._lock .notify ()
370- finally :
371- self ._lock .release ()
372360
373361 def close (self ):
374362 """Close all connections in the pool."""
375- self ._lock .acquire ()
376- try :
363+ with self ._lock :
377364 while self ._idle_cache : # close all idle connections
378365 con = self ._idle_cache .pop (0 )
379366 try :
@@ -389,8 +376,6 @@ def close(self):
389376 pass
390377 self ._connections -= 1
391378 self ._lock .notifyAll ()
392- finally :
393- self ._lock .release ()
394379
395380 def __del__ (self ):
396381 """Delete the pool."""
0 commit comments