import threading
class ThreadSafeFile:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.lock = threading.Lock()
self.file = None
def __enter__(self):
self.lock.acquire()
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
self.lock.release()
def write_to_file():
with ThreadSafeFile('test.txt', 'a') as file:
file.write('This is a test from a thread.\n')
threads = []
for _ in range(5):
thread = threading.Thread(target=write_to_file)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()