MST

星途 面试题库

面试题:Python多线程文件处理的资源竞争与优化

假设你有一个多线程程序,多个线程需要同时对同一个大文件进行读取和写入操作。如何使用Python的线程锁、信号量等机制来避免资源竞争问题,同时尽量优化程序性能以提高文件处理效率?请给出具体的代码实现思路及关键代码片段。
20.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

代码实现思路

  1. 导入必要的模块:使用threading模块来处理多线程,time模块用于模拟一些耗时操作。
  2. 创建锁和信号量:使用threading.Lock来确保同一时间只有一个线程能对文件进行写入操作,使用threading.Semaphore来控制同时访问文件的线程数量,以优化性能。
  3. 定义线程函数:在函数中,获取锁或信号量后进行文件操作,操作完成后释放锁或信号量。

关键代码片段

import threading
import time


# 创建锁
file_lock = threading.Lock()
# 创建信号量,允许同时有3个线程访问文件
semaphore = threading.Semaphore(3)


def read_write_file(file_path, operation):
    with semaphore:
        with file_lock:
            with open(file_path, operation) as f:
                if operation == 'r':
                    data = f.read()
                    print(f"Read data: {data}")
                elif operation == 'w':
                    f.write("Some data\n")
                    print("Data written")
                time.sleep(1)  # 模拟一些耗时操作


if __name__ == "__main__":
    file_path = "test.txt"
    # 创建读线程
    read_thread = threading.Thread(target=read_write_file, args=(file_path, 'r'))
    # 创建写线程
    write_thread = threading.Thread(target=read_write_file, args=(file_path, 'w'))
    read_thread.start()
    write_thread.start()
    read_thread.join()
    write_thread.join()

在上述代码中:

  • file_lock用于确保文件的读写操作不会冲突,特别是在写入时。
  • semaphore控制同时访问文件的线程数量,避免过多线程同时竞争文件资源,提升性能。
  • with语句确保锁和信号量在使用完后正确释放。