Skip to content

Commit 15bc6d2

Browse files
committed
bpo-22087: Fix Policy.get_event_loop() to detect fork and return a new loop.
Original patch by Dan O'Reilly.
1 parent 4fadf0c commit 15bc6d2

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

Lib/asyncio/events.py

+7
Original file line numberDiff line numberDiff line change
@@ -625,16 +625,23 @@ class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
625625

626626
class _Local(threading.local):
627627
_loop = None
628+
_pid = None
628629
_set_called = False
629630

630631
def __init__(self):
631632
self._local = self._Local()
633+
self._local._pid = os.getpid()
632634

633635
def get_event_loop(self):
634636
"""Get the event loop.
635637
636638
This may be None or an instance of EventLoop.
637639
"""
640+
if self._local._pid != os.getpid():
641+
# If we detect we're in a child process forked by multiprocessing,
642+
# we reset self._local so that we'll get a new event loop.
643+
self._local = self._Local()
644+
638645
if (self._local._loop is None and
639646
not self._local._set_called and
640647
isinstance(threading.current_thread(), threading._MainThread)):

Lib/test/test_asyncio/test_unix_events.py

+21
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import tempfile
1414
import threading
1515
import unittest
16+
import multiprocessing
1617
from unittest import mock
1718
from test import support
1819

@@ -1804,6 +1805,26 @@ def create_watcher(self):
18041805
return asyncio.FastChildWatcher()
18051806

18061807

1808+
class ForkedProcessTests(unittest.TestCase):
1809+
def setUp(self):
1810+
self.parent_loop = asyncio.SelectorEventLoop()
1811+
asyncio.set_event_loop(self.parent_loop)
1812+
self.ctx = multiprocessing.get_context("fork")
1813+
1814+
def _check_loops_not_equal(self, old_loop):
1815+
loop = asyncio.get_event_loop()
1816+
sys.exit(loop is old_loop)
1817+
1818+
def test_new_loop_in_child(self):
1819+
p = self.ctx.Process(target=self._check_loops_not_equal,
1820+
args=(self.parent_loop,))
1821+
p.start()
1822+
p.join()
1823+
self.assertEqual(p.exitcode, 0,
1824+
"Child process inherited parent's event loop")
1825+
self.parent_loop.close()
1826+
1827+
18071828
class PolicyTests(unittest.TestCase):
18081829

18091830
def create_policy(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix Policy.get_event_loop() to detect fork and return a new loop.
2+
3+
Original patch by Dan O'Reilly.

0 commit comments

Comments
 (0)