@@ -305,8 +305,8 @@ class Pool:
305305 __slots__ = ('_queue' , '_loop' , '_minsize' , '_maxsize' ,
306306 '_init' , '_connect_args' , '_connect_kwargs' ,
307307 '_working_addr' , '_working_config' , '_working_params' ,
308- '_holders' , '_initialized' , '_closing ' , '_closed ' ,
309- '_connection_class' , '_generation' )
308+ '_holders' , '_initialized' , '_initializing ' , '_closing ' ,
309+ '_closed' , ' _connection_class' , '_generation' )
310310
311311 def __init__ (self , * connect_args ,
312312 min_size ,
@@ -359,6 +359,7 @@ def __init__(self, *connect_args,
359359
360360 self ._holders = []
361361 self ._initialized = False
362+ self ._initializing = False
362363 self ._queue = asyncio .LifoQueue (maxsize = self ._maxsize , loop = self ._loop )
363364
364365 self ._working_addr = None
@@ -387,9 +388,20 @@ def __init__(self, *connect_args,
387388 async def _async__init__ (self ):
388389 if self ._initialized :
389390 return
391+ if self ._initializing :
392+ raise exceptions .InterfaceError (
393+ 'pool is being initialized in another task' )
390394 if self ._closed :
391395 raise exceptions .InterfaceError ('pool is closed' )
396+ self ._initializing = True
397+ try :
398+ await self ._initialize ()
399+ return self
400+ finally :
401+ self ._initializing = False
402+ self ._initialized = True
392403
404+ async def _initialize (self ):
393405 if self ._minsize :
394406 # Since we use a LIFO queue, the first items in the queue will be
395407 # the last ones in `self._holders`. We want to pre-connect the
@@ -412,9 +424,6 @@ async def _async__init__(self):
412424
413425 await asyncio .gather (* connect_tasks , loop = self ._loop )
414426
415- self ._initialized = True
416- return self
417-
418427 def set_connect_args (self , dsn = None , ** connect_kwargs ):
419428 r"""Set the new connection arguments for this pool.
420429
@@ -703,6 +712,11 @@ async def expire_connections(self):
703712
704713 def _check_init (self ):
705714 if not self ._initialized :
715+ if self ._initializing :
716+ raise exceptions .InterfaceError (
717+ 'pool is being initialized, but not yet ready: '
718+ 'likely there is a race between creating a pool and '
719+ 'using it' )
706720 raise exceptions .InterfaceError ('pool is not initialized' )
707721 if self ._closed :
708722 raise exceptions .InterfaceError ('pool is closed' )
0 commit comments