From 463a7e458f62c4ded190ed0d94828c2ce8d3b4d3 Mon Sep 17 00:00:00 2001 From: Mathias Stearn Date: Tue, 19 Oct 2010 17:42:14 -0400 Subject: [PATCH] Reset connection pool after fork PYTHON-166 --- pymongo/connection.py | 18 +++++++++++++----- test/test_connection.py | 1 + 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pymongo/connection.py b/pymongo/connection.py index ce3faecc9f..230467c2d1 100644 --- a/pymongo/connection.py +++ b/pymongo/connection.py @@ -135,22 +135,30 @@ class _Pool(threading.local): """ # Non thread-locals - __slots__ = ["sockets", "socket_factory", "pool_size"] + __slots__ = ["sockets", "socket_factory", "pool_size", "pid"] + + # thread-local default sock = None def __init__(self, socket_factory): + self.pid = os.getpid() self.pool_size = 10 self.socket_factory = socket_factory if not hasattr(self, "sockets"): self.sockets = [] + def socket(self): - # we store the pid here to avoid issues with fork / - # multiprocessing - see - # test.test_connection:TestConnection.test_fork for an example - # of what could go wrong otherwise + # We use the pid here to avoid issues with fork / multiprocessing. + # See test.test_connection:TestConnection.test_fork for an example of + # what could go wrong otherwise pid = os.getpid() + if pid != self.pid: + self.sock = None + self.sockets = [] + self.pid = pid + if self.sock is not None and self.sock[0] == pid: return self.sock[1] diff --git a/test/test_connection.py b/test/test_connection.py index c940e7cd36..a8571bab68 100644 --- a/test/test_connection.py +++ b/test/test_connection.py @@ -320,6 +320,7 @@ def test_fork(self): # Failure occurs if the connection is used before the fork db.test.find_one() + db.connection.end_request() def loop(pipe): while True: