diff --git a/pymongo/pool.py b/pymongo/pool.py index a18e005ba5..92814e8570 100644 --- a/pymongo/pool.py +++ b/pymongo/pool.py @@ -1257,12 +1257,15 @@ def _get_socket(self, all_credentials): if not self._socket_semaphore.acquire( True, self.opts.wait_queue_timeout): self._raise_wait_queue_timeout() - with self.lock: - self.active_sockets += 1 # We've now acquired the semaphore and must release it on error. sock_info = None + incremented = False try: + with self.lock: + self.active_sockets += 1 + incremented = True + while sock_info is None: try: with self.lock: @@ -1279,8 +1282,10 @@ def _get_socket(self, all_credentials): # We checked out a socket but authentication failed. sock_info.close_socket(ConnectionClosedReason.ERROR) self._socket_semaphore.release() - with self.lock: - self.active_sockets -= 1 + + if incremented: + with self.lock: + self.active_sockets -= 1 if self.enabled_for_cmap: self.opts.event_listeners.publish_connection_check_out_failed( diff --git a/pymongo/thread_util.py b/pymongo/thread_util.py index 3869ec322f..0cf0a127f2 100644 --- a/pymongo/thread_util.py +++ b/pymongo/thread_util.py @@ -40,22 +40,21 @@ def acquire(self, blocking=True, timeout=None): raise ValueError("can't specify timeout for non-blocking acquire") rc = False endtime = None - self._cond.acquire() - while self._value == 0: - if not blocking: - break - if timeout is not None: - if endtime is None: - endtime = _time() + timeout - else: - timeout = endtime - _time() - if timeout <= 0: - break - self._cond.wait(timeout) - else: - self._value = self._value - 1 - rc = True - self._cond.release() + with self._cond: + while self._value == 0: + if not blocking: + break + if timeout is not None: + if endtime is None: + endtime = _time() + timeout + else: + timeout = endtime - _time() + if timeout <= 0: + break + self._cond.wait(timeout) + else: + self._value = self._value - 1 + rc = True return rc __enter__ = acquire