MST
星途 面试题库

面试题:C语言系统调用封装优化:多线程文件读写

假设你已经完成了基本的文件操作的系统调用封装,现在要求你在此基础上,利用多线程技术优化文件的读写操作。请描述实现思路,并给出关键代码片段。需要考虑线程同步问题,避免数据竞争。
16.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 任务划分:将文件读写任务划分为多个子任务,每个子任务由一个线程负责。例如,可以按文件块来划分读或写的任务。
  2. 线程同步:使用互斥锁(Mutex)来保护共享资源,如文件指针、缓冲区等,避免多个线程同时访问导致数据竞争。
  3. 条件变量(可选):若需要线程之间进行协作,如一个线程写数据到缓冲区,另一个线程从缓冲区读数据,可以使用条件变量来协调线程的执行顺序。

关键代码片段(以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;
}

在上述代码中:

  1. fileMutex 用于保护共享资源,如文件操作和 buffer
  2. cv 是条件变量,用于线程间协作,dataReady 是与之配合的标志位。
  3. readFromFile 函数读取文件内容到 buffer,并设置 dataReadytrue,然后通知等待的线程。
  4. writeToFile 函数等待 dataReadytrue,然后将 buffer 内容写入文件。