Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Adds test for multithreaded writes to files.
Multithreaded writes to files (including standard calls to print() from
threads) can result in assertion failures and potentially missed output due to
race conditions in _io_TextIOWrapper_write_impl and _textiowrapper_writeflush.

See: #118138
  • Loading branch information
elistevens committed May 17, 2024
commit dca6eb690f19ce49af1d570623ae26f402d7d285
36 changes: 36 additions & 0 deletions Lib/test/test_io_threading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import unittest
from concurrent.futures import ThreadPoolExecutor


NUM_THREADS = 100
NUM_LOOPS = 10

def looping_print_to_file(f, i):
for j in range(NUM_LOOPS):
# p = 'x' * 90 + '123456789'
p = f"{i:2}i,{j}j\n" + '0123456789' * 10
print(p, file=f)

class IoThreadingTestCase(unittest.TestCase):
def test_io_threading(self):
with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
with open('test_io_threading.out', 'w') as f:
for i in range(NUM_THREADS):
executor.submit(looping_print_to_file, f, i)

executor.shutdown(wait=True)

with open('test_io_threading.out', 'r') as f:
lines = set(x.rstrip() for x in f.readlines() if ',' in x)

assert len(lines) == NUM_THREADS * NUM_LOOPS, repr(len(lines))

for i in range(NUM_THREADS):
for j in range(NUM_LOOPS):
p = f"{i:2}i,{j}j"

assert p in lines, repr(p)


if __name__ == "__main__":
unittest.main()
4 changes: 4 additions & 0 deletions Modules/_io/textio.c
Original file line number Diff line number Diff line change
Expand Up @@ -1729,6 +1729,10 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
Py_DECREF(b);
return NULL;
}
// The assumption that self won't have been modified from another
// thread between the flush above and the assignment below is
// incorrect.
assert(self->pending_bytes == NULL);
self->pending_bytes = b;
}
else if (!PyList_CheckExact(self->pending_bytes)) {
Expand Down