面试题答案
一键面试代码实现思路
- 导入必要的模块:使用
threading
模块来处理多线程,time
模块用于模拟一些耗时操作。 - 创建锁和信号量:使用
threading.Lock
来确保同一时间只有一个线程能对文件进行写入操作,使用threading.Semaphore
来控制同时访问文件的线程数量,以优化性能。 - 定义线程函数:在函数中,获取锁或信号量后进行文件操作,操作完成后释放锁或信号量。
关键代码片段
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
语句确保锁和信号量在使用完后正确释放。