Skip to content

Commit ff5f1ce

Browse files
authored
PYTHON-1704 Close periodic task thread when client is closed (mongodb#389)
1 parent 1d8c739 commit ff5f1ce

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

pymongo/mongo_client.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1030,8 +1030,9 @@ def close(self):
10301030
session_ids = self._topology.pop_all_sessions()
10311031
if session_ids:
10321032
self._end_sessions(session_ids)
1033-
# Run _process_periodic_tasks to send pending killCursor requests
1034-
# before closing the topology.
1033+
# Stop the periodic task thread and then run _process_periodic_tasks
1034+
# to send pending killCursor requests before closing the topology.
1035+
self._kill_cursors_executor.close()
10351036
self._process_periodic_tasks()
10361037
self._topology.close()
10371038

@@ -1071,6 +1072,8 @@ def _get_topology(self):
10711072
launches the connection process in the background.
10721073
"""
10731074
self._topology.open()
1075+
with self.__lock:
1076+
self._kill_cursors_executor.open()
10741077
return self._topology
10751078

10761079
@contextlib.contextmanager
@@ -1136,10 +1139,6 @@ def _send_message_with_response(self, operation, exhaust=False,
11361139
- `address` (optional): Optional address when sending a message
11371140
to a specific server, used for getMore.
11381141
"""
1139-
with self.__lock:
1140-
# If needed, restart kill-cursors thread after a fork.
1141-
self._kill_cursors_executor.open()
1142-
11431142
topology = self._get_topology()
11441143
if address:
11451144
server = topology.select_server_by_address(address)

test/test_client.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,23 @@ def test_close_kills_cursors(self):
640640
self.client._process_periodic_tasks()
641641
self.assertFalse(self.client._topology._opened)
642642

643+
def test_close_stops_kill_cursors_thread(self):
644+
client = rs_client()
645+
client.test.test.find_one()
646+
self.assertFalse(client._kill_cursors_executor._stopped)
647+
648+
# Closing the client should stop the thread.
649+
client.close()
650+
self.assertTrue(client._kill_cursors_executor._stopped)
651+
652+
# Reusing the closed client should restart the thread.
653+
client.admin.command('isMaster')
654+
self.assertFalse(client._kill_cursors_executor._stopped)
655+
656+
# Again, closing the client should stop the thread.
657+
client.close()
658+
self.assertTrue(client._kill_cursors_executor._stopped)
659+
643660
def test_bad_uri(self):
644661
with self.assertRaises(InvalidURI):
645662
MongoClient("http://localhost")

0 commit comments

Comments
 (0)