Skip to content

Commit fa2a9a1

Browse files
committed
bpo-22087: Restructure code to be more robust and safe
1 parent e2b340a commit fa2a9a1

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

Lib/asyncio/events.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -628,20 +628,25 @@ class _Local(threading.local):
628628
_pid = None
629629
_set_called = False
630630

631+
def __init__(self):
632+
super().__init__()
633+
self._pid = os.getpid()
634+
631635
def __init__(self):
632636
self._local = self._Local()
633-
self._local._pid = os.getpid()
634-
635-
def get_event_loop(self):
636-
"""Get the event loop.
637637

638-
This may be None or an instance of EventLoop.
639-
"""
638+
def _check_pid(self):
640639
if self._local._pid != os.getpid():
641640
# If we detect we're in a child process forked by multiprocessing,
642641
# we reset self._local so that we'll get a new event loop.
643642
self._local = self._Local()
644643

644+
def get_event_loop(self):
645+
"""Get the event loop.
646+
647+
This may be None or an instance of EventLoop.
648+
"""
649+
self._check_pid()
645650
if (self._local._loop is None and
646651
not self._local._set_called and
647652
isinstance(threading.current_thread(), threading._MainThread)):
@@ -655,6 +660,7 @@ def get_event_loop(self):
655660

656661
def set_event_loop(self, loop):
657662
"""Set the event loop."""
663+
self._check_pid()
658664
self._local._set_called = True
659665
assert loop is None or isinstance(loop, AbstractEventLoop)
660666
self._local._loop = loop

Lib/test/test_asyncio/test_unix_events.py

+5
Original file line numberDiff line numberDiff line change
@@ -1874,8 +1874,11 @@ def test_get_child_watcher_with_mainloop_existing(self):
18741874
loop.close()
18751875

18761876
def test_get_child_watcher_thread(self):
1877+
success = False
18771878

18781879
def f():
1880+
nonlocal success
1881+
18791882
policy.set_event_loop(policy.new_event_loop())
18801883

18811884
self.assertIsInstance(policy.get_event_loop(),
@@ -1886,12 +1889,14 @@ def f():
18861889
self.assertIsNone(watcher._loop)
18871890

18881891
policy.get_event_loop().close()
1892+
success = True
18891893

18901894
policy = self.create_policy()
18911895

18921896
th = threading.Thread(target=f)
18931897
th.start()
18941898
th.join()
1899+
self.assertTrue(success)
18951900

18961901
def test_child_watcher_replace_mainloop_existing(self):
18971902
policy = self.create_policy()

0 commit comments

Comments
 (0)