bpo-31976: Fix race condition when flushing a file is slow. (#4331)

This commit is contained in:
benfogle 2017-11-10 16:03:40 -05:00 committed by Antoine Pitrou
parent 4652bf2acc
commit 9703f092ab
4 changed files with 58 additions and 8 deletions

View file

@ -1188,11 +1188,11 @@ class BufferedWriter(_BufferedIOMixin):
return self.raw.writable()
def write(self, b):
if self.closed:
raise ValueError("write to closed file")
if isinstance(b, str):
raise TypeError("can't write str to binary stream")
with self._write_lock:
if self.closed:
raise ValueError("write to closed file")
# XXX we can implement some more tricks to try and avoid
# partial writes
if len(self._write_buf) > self.buffer_size:
@ -1253,6 +1253,21 @@ class BufferedWriter(_BufferedIOMixin):
self._flush_unlocked()
return _BufferedIOMixin.seek(self, pos, whence)
def close(self):
with self._write_lock:
if self.raw is None or self.closed:
return
# We have to release the lock and call self.flush() (which will
# probably just re-take the lock) in case flush has been overridden in
# a subclass or the user set self.flush to something. This is the same
# behavior as the C implementation.
try:
# may raise BlockingIOError or BrokenPipeError etc
self.flush()
finally:
with self._write_lock:
self.raw.close()
class BufferedRWPair(BufferedIOBase):