MST

星途 面试题库

面试题:Python多线程异常处理与资源清理

假设在一个Python多线程程序中,线程在执行文件读取操作时可能引发异常,在捕获异常后如何确保文件资源被正确关闭,同时保证多线程环境下的资源安全?请给出代码示例。
36.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading
import time

class FileReader:
    def __init__(self, file_path):
        self.file_path = file_path
        self.lock = threading.Lock()

    def read_file(self):
        with self.lock:
            try:
                with open(self.file_path, 'r') as file:
                    content = file.read()
                    print(f"线程 {threading.current_thread().name} 读取到内容: {content}")
            except FileNotFoundError as e:
                print(f"线程 {threading.current_thread().name} 捕获到异常: {e}")
            except Exception as e:
                print(f"线程 {threading.current_thread().name} 捕获到其他异常: {e}")


if __name__ == "__main__":
    file_path = "test.txt"
    reader = FileReader(file_path)

    threads = []
    for i in range(3):
        thread = threading.Thread(target=reader.read_file)
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

在上述代码中:

  1. FileReader 类封装了文件读取的操作,并使用 threading.Lock 来确保多线程环境下对文件操作的资源安全。
  2. 使用 with open 语句来读取文件,这可以保证无论在读取过程中是否发生异常,文件都会被正确关闭。
  3. read_file 方法中,使用 try - except 块捕获可能发生的异常,并在捕获到异常时打印相应的信息。

这样既确保了文件资源被正确关闭,又保证了多线程环境下的资源安全。