import os, threading file = open('logthred.log', 'a') lock = threading.RLock() class IOThread(threading.Thread): def __init__(self, numLoops, n): threading.Thread.__init__(self) self.name = 'thread-%02d' % n self.numLoops = numLoops def run(self): global file for x in range(0, self.numLoops): os.system('cd . > blah.txt') os.system('del blah.txt') s = 'This is log message ' + str(x) + ' from ' + self.name + ' and I think this should be a little longer, so I\'ll add some more data here because perhaps the size of the individual log message is a factor. Who knows for sure until this simple test fails.' lock.acquire() try: if file.tell() + len(s) < 2048: print >> file, s else: file.close() dfn = 'logthred.log.1' if os.path.exists(dfn): os.remove(dfn) os.rename('logthred.log', dfn) file = open('logthred.log', 'a') finally: lock.release() if __name__=="__main__": numThreads = 10 numLoops = 100 # Create and execute threads threads = [] for x in range(0, numThreads): t = IOThread(numLoops, x) print t.name threads.append(t) t.start() for t in threads: print "Joining", t.name t.join()