MST

星途 面试题库

面试题:Python中如何通过上下文管理器实现线程安全的文件操作

在Python中,文件操作在多线程环境下可能会出现数据竞争问题。请你编写一个上下文管理器,确保在多线程环境下对文件的读写操作是线程安全的。可以使用`threading.Lock`来辅助实现,要求展示完整的代码,包括上下文管理器的定义以及多线程环境下使用该上下文管理器操作文件的示例。
12.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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()