From a316c6576d2fae0b27f55fef8130a3fa4995f2a3 Mon Sep 17 00:00:00 2001 From: "A. Jesse Jiryu Davis" Date: Mon, 15 Jun 2015 13:29:03 -0400 Subject: [PATCH] PYTHON-939 - Stop background threads quicker. Instead of signaling each thread to close, then waiting for it to finish before signaling the next, instead signal all threads to close and let them stop in parallel before joining any. Additionally, spend less time holding strong references to threads. --- pymongo/periodic_executor.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 540903736..c630b9258 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -132,10 +132,19 @@ def _on_executor_deleted(ref): def _shutdown_executors(): # Copy the set. Stopping threads has the side effect of removing executors. executors = list(_EXECUTORS) + + # First signal all executors to close... for ref in executors: - executor = ref() - if executor: - executor.close() - executor.join(10) + try: + ref().close() + except ReferenceError: + pass + + # ...then try to join them. + for ref in executors: + try: + ref().join(1) + except ReferenceError: + pass atexit.register(_shutdown_executors)