@@ -305,8 +305,8 @@ class Pool:
305
305
__slots__ = ('_queue' , '_loop' , '_minsize' , '_maxsize' ,
306
306
'_init' , '_connect_args' , '_connect_kwargs' ,
307
307
'_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' )
310
310
311
311
def __init__ (self , * connect_args ,
312
312
min_size ,
@@ -359,6 +359,7 @@ def __init__(self, *connect_args,
359
359
360
360
self ._holders = []
361
361
self ._initialized = False
362
+ self ._initializing = False
362
363
self ._queue = asyncio .LifoQueue (maxsize = self ._maxsize , loop = self ._loop )
363
364
364
365
self ._working_addr = None
@@ -387,9 +388,20 @@ def __init__(self, *connect_args,
387
388
async def _async__init__ (self ):
388
389
if self ._initialized :
389
390
return
391
+ if self ._initializing :
392
+ raise exceptions .InterfaceError (
393
+ 'pool is being initialized in another task' )
390
394
if self ._closed :
391
395
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
392
403
404
+ async def _initialize (self ):
393
405
if self ._minsize :
394
406
# Since we use a LIFO queue, the first items in the queue will be
395
407
# the last ones in `self._holders`. We want to pre-connect the
@@ -412,9 +424,6 @@ async def _async__init__(self):
412
424
413
425
await asyncio .gather (* connect_tasks , loop = self ._loop )
414
426
415
- self ._initialized = True
416
- return self
417
-
418
427
def set_connect_args (self , dsn = None , ** connect_kwargs ):
419
428
r"""Set the new connection arguments for this pool.
420
429
@@ -703,6 +712,11 @@ async def expire_connections(self):
703
712
704
713
def _check_init (self ):
705
714
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' )
706
720
raise exceptions .InterfaceError ('pool is not initialized' )
707
721
if self ._closed :
708
722
raise exceptions .InterfaceError ('pool is closed' )
0 commit comments