Skip to content

Commit 463a7e4

Browse files
committed
Reset connection pool after fork PYTHON-166
1 parent a19fd9b commit 463a7e4

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

pymongo/connection.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,22 +135,30 @@ class _Pool(threading.local):
135135
"""
136136

137137
# Non thread-locals
138-
__slots__ = ["sockets", "socket_factory", "pool_size"]
138+
__slots__ = ["sockets", "socket_factory", "pool_size", "pid"]
139+
140+
# thread-local default
139141
sock = None
140142

141143
def __init__(self, socket_factory):
144+
self.pid = os.getpid()
142145
self.pool_size = 10
143146
self.socket_factory = socket_factory
144147
if not hasattr(self, "sockets"):
145148
self.sockets = []
146149

150+
147151
def socket(self):
148-
# we store the pid here to avoid issues with fork /
149-
# multiprocessing - see
150-
# test.test_connection:TestConnection.test_fork for an example
151-
# of what could go wrong otherwise
152+
# We use the pid here to avoid issues with fork / multiprocessing.
153+
# See test.test_connection:TestConnection.test_fork for an example of
154+
# what could go wrong otherwise
152155
pid = os.getpid()
153156

157+
if pid != self.pid:
158+
self.sock = None
159+
self.sockets = []
160+
self.pid = pid
161+
154162
if self.sock is not None and self.sock[0] == pid:
155163
return self.sock[1]
156164

test/test_connection.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ def test_fork(self):
320320

321321
# Failure occurs if the connection is used before the fork
322322
db.test.find_one()
323+
db.connection.end_request()
323324

324325
def loop(pipe):
325326
while True:

0 commit comments

Comments
 (0)