面试题答案
一键面试实现思路
- 任务划分:将文件读写任务划分为多个子任务,每个子任务由一个线程负责。例如,可以按文件块来划分读或写的任务。
- 线程同步:使用互斥锁(Mutex)来保护共享资源,如文件指针、缓冲区等,避免多个线程同时访问导致数据竞争。
- 条件变量(可选):若需要线程之间进行协作,如一个线程写数据到缓冲区,另一个线程从缓冲区读数据,可以使用条件变量来协调线程的执行顺序。
关键代码片段(以C++为例)
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <vector>
#include <condition_variable>
std::mutex fileMutex;
std::condition_variable cv;
std::vector<char> buffer;
bool dataReady = false;
// 写线程函数
void writeToFile(const std::string& filename) {
std::ofstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Failed to open file for writing." << std::endl;
return;
}
std::unique_lock<std::mutex> lock(fileMutex);
cv.wait(lock, []{ return dataReady; });
file.write(buffer.data(), buffer.size());
file.close();
}
// 读线程函数
void readFromFile(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Failed to open file for reading." << std::endl;
return;
}
file.seekg(0, std::ios::end);
size_t fileSize = file.tellg();
file.seekg(0, std::ios::beg);
buffer.resize(fileSize);
file.read(buffer.data(), fileSize);
file.close();
{
std::unique_lock<std::mutex> lock(fileMutex);
dataReady = true;
}
cv.notify_one();
}
int main() {
std::string filename = "example.bin";
std::thread writer(writeToFile, filename);
std::thread reader(readFromFile, filename);
reader.join();
writer.join();
return 0;
}
在上述代码中:
fileMutex
用于保护共享资源,如文件操作和buffer
。cv
是条件变量,用于线程间协作,dataReady
是与之配合的标志位。readFromFile
函数读取文件内容到buffer
,并设置dataReady
为true
,然后通知等待的线程。writeToFile
函数等待dataReady
为true
,然后将buffer
内容写入文件。