Perhaps it’s time to introduce a mutex to protect the TextIOWrapper object’s internal structures? I don’t think trying to make the algorithm race-free otherwise is a robust approach.
Also, I’ll note that “output of uninitialized memory” is a potential security issue (“uninitialized” memory could be previously-allocated memory that contained secrets).
cc @gpshead for visibility.