summaryrefslogtreecommitdiffstats
path: root/Modules
diff options
context:
space:
mode:
authorRadislav Chugunov <52372310+chgnrdv@users.noreply.github.com>2024-06-03 07:47:36 (GMT)
committerGitHub <noreply@github.com>2024-06-03 07:47:36 (GMT)
commit52586f930f62bd80374f0f240a4ecce0c0238174 (patch)
tree9a58cd4a036e0ef7db5abf981afc88495311fdb4 /Modules
parent3ea9b92086240b2f38a74c6945e7a723b480cefe (diff)
downloadcpython-52586f930f62bd80374f0f240a4ecce0c0238174.zip
cpython-52586f930f62bd80374f0f240a4ecce0c0238174.tar.gz
cpython-52586f930f62bd80374f0f240a4ecce0c0238174.tar.bz2
gh-119506: fix `_io.TextIOWrapper.write()` write during flush (#119507)
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
Diffstat (limited to 'Modules')
-rw-r--r--Modules/_io/textio.c31
1 files changed, 22 insertions, 9 deletions
diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c
index 9dff8ea..c162d81 100644
--- a/Modules/_io/textio.c
+++ b/Modules/_io/textio.c
@@ -1719,16 +1719,26 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
bytes_len = PyBytes_GET_SIZE(b);
}
- if (self->pending_bytes == NULL) {
- self->pending_bytes_count = 0;
- self->pending_bytes = b;
- }
- else if (self->pending_bytes_count + bytes_len > self->chunk_size) {
- // Prevent to concatenate more than chunk_size data.
- if (_textiowrapper_writeflush(self) < 0) {
- Py_DECREF(b);
- return NULL;
+ // We should avoid concatinating huge data.
+ // Flush the buffer before adding b to the buffer if b is not small.
+ // https://github.com/python/cpython/issues/87426
+ if (bytes_len >= self->chunk_size) {
+ // _textiowrapper_writeflush() calls buffer.write().
+ // self->pending_bytes can be appended during buffer->write()
+ // or other thread.
+ // We need to loop until buffer becomes empty.
+ // https://github.com/python/cpython/issues/118138
+ // https://github.com/python/cpython/issues/119506
+ while (self->pending_bytes != NULL) {
+ if (_textiowrapper_writeflush(self) < 0) {
+ Py_DECREF(b);
+ return NULL;
+ }
}
+ }
+
+ if (self->pending_bytes == NULL) {
+ assert(self->pending_bytes_count == 0);
self->pending_bytes = b;
}
else if (!PyList_CheckExact(self->pending_bytes)) {
@@ -1737,6 +1747,9 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
Py_DECREF(b);
return NULL;
}
+ // Since Python 3.12, allocating GC object won't trigger GC and release
+ // GIL. See https://github.com/python/cpython/issues/97922
+ assert(!PyList_CheckExact(self->pending_bytes));
PyList_SET_ITEM(list, 0, self->pending_bytes);
PyList_SET_ITEM(list, 1, b);
self->pending_bytes = list;