create and delete filesperthread temp files via tempfile temporaryfile in each of numthreads threads recording the number of successes and failures a failure is a bug in tempfile and may be due to trying to create more than one tempfile with the same name trying to delete a tempfile that doesn t still exist something we ve never seen before by default numthreads 20 and filesperthread 50 this is enough to create about 150 failures per run under win98se in 2 0 and runs pretty quickly guido reports needing to boost filesperthread to 500 before provoking a 2 0 failure under linux
import tempfile

from test.support import threading_helper
import unittest
import io
import threading
from traceback import print_exc

threading_helper.requires_working_threading(module=True)

NUM_THREADS = 20
FILES_PER_THREAD = 50


startEvent = threading.Event()


class TempFileGreedy(threading.Thread):
    error_count = 0
    ok_count = 0

    def run(self):
        self.errors = io.StringIO()
        startEvent.wait()
        for i in range(FILES_PER_THREAD):
            try:
                f = tempfile.TemporaryFile("w+b")
                f.close()
            except:
                self.error_count += 1
                print_exc(file=self.errors)
            else:
                self.ok_count += 1


class ThreadedTempFileTest(unittest.TestCase):
    def test_main(self):
        threads = [TempFileGreedy() for i in range(NUM_THREADS)]
        with threading_helper.start_threads(threads, startEvent.set):
            pass
        ok = sum(t.ok_count for t in threads)
        errors = [str(t.name) + str(t.errors.getvalue())
                  for t in threads if t.error_count]

        msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
            '\n'.join(errors))
        self.assertEqual(errors, [], msg)
        self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD)

if __name__ == "__main__":
    unittest.main()