Skip to content

Commit 1b0f0e3

Browse files
authored
bpo-39651: Fix asyncio proactor _write_to_self() (GH-22197)
Fix a race condition in the call_soon_threadsafe() method of asyncio.ProactorEventLoop: do nothing if the self-pipe socket has been closed.
1 parent 7e711ea commit 1b0f0e3

File tree

3 files changed

+23
-9
lines changed

3 files changed

+23
-9
lines changed

Lib/asyncio/proactor_events.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -793,8 +793,17 @@ def _loop_self_reading(self, f=None):
793793
f.add_done_callback(self._loop_self_reading)
794794

795795
def _write_to_self(self):
796+
# This may be called from a different thread, possibly after
797+
# _close_self_pipe() has been called or even while it is
798+
# running. Guard for self._csock being None or closed. When
799+
# a socket is closed, send() raises OSError (with errno set to
800+
# EBADF, but let's not rely on the exact error code).
801+
csock = self._csock
802+
if csock is None:
803+
return
804+
796805
try:
797-
self._csock.send(b'\0')
806+
csock.send(b'\0')
798807
except OSError:
799808
if self._debug:
800809
logger.debug("Fail to write a null byte into the "

Lib/asyncio/selector_events.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -133,14 +133,16 @@ def _write_to_self(self):
133133
# a socket is closed, send() raises OSError (with errno set to
134134
# EBADF, but let's not rely on the exact error code).
135135
csock = self._csock
136-
if csock is not None:
137-
try:
138-
csock.send(b'\0')
139-
except OSError:
140-
if self._debug:
141-
logger.debug("Fail to write a null byte into the "
142-
"self-pipe socket",
143-
exc_info=True)
136+
if csock is None:
137+
return
138+
139+
try:
140+
csock.send(b'\0')
141+
except OSError:
142+
if self._debug:
143+
logger.debug("Fail to write a null byte into the "
144+
"self-pipe socket",
145+
exc_info=True)
144146

145147
def _start_serving(self, protocol_factory, sock,
146148
sslcontext=None, server=None, backlog=100,
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a race condition in the ``call_soon_threadsafe()`` method of
2+
``asyncio.ProactorEventLoop``: do nothing if the self-pipe socket has been
3+
closed.

0 commit comments

Comments
 (0)