Index: Modules/_io/textio.c =================================================================== --- Modules/_io/textio.c (revision 73674) +++ Modules/_io/textio.c (working copy) @@ -1213,11 +1213,18 @@ static int _textiowrapper_writeflush(textio *self) { - PyObject *b, *ret; + PyObject *pending, *b, *ret; if (self->pending_bytes == NULL) return 0; - b = _PyBytes_Join(_PyIO_empty_bytes, self->pending_bytes); + + pending = self->pending_bytes; + Py_INCREF(pending); + self->pending_bytes_count = 0; + Py_CLEAR(self->pending_bytes); + + b = _PyBytes_Join(_PyIO_empty_bytes, pending); + Py_DECREF(pending); if (b == NULL) return -1; ret = PyObject_CallMethodObjArgs(self->buffer, @@ -1226,8 +1233,6 @@ if (ret == NULL) return -1; Py_DECREF(ret); - Py_CLEAR(self->pending_bytes); - self->pending_bytes_count = 0; return 0; } Index: Lib/test/test_io.py =================================================================== --- Lib/test/test_io.py (revision 73674) +++ Lib/test/test_io.py (working copy) @@ -2031,6 +2031,26 @@ self.assertEqual(f.errors, "replace") + def test_threads_write(self): + # Issue6750: concurrent writes could duplicate data + event = threading.Event() + with self.open(support.TESTFN, "w", buffering=1) as f: + def run(n): + text = "Thread%03d\n" % n + event.wait() + f.write(text) + threads = [threading.Thread(target=lambda n=x: run(n)) for x in range(20)] + for t in threads: + t.start() + time.sleep(0.02) + event.set() + for t in threads: + t.join() + with self.open(support.TESTFN) as f: + content = f.read() + for n in range(20): + self.assertEquals(content.count("Thread%03d\n" % n), 1) + class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self):