以下是一个简单的c++多线程同时读取一个大文件的数据,并写入同一个文件的示例代码:

#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <vector>

const int BUFFER_SIZE = 1024 * 1024; // 缓冲区大小
std::mutex mtx; // 互斥锁

void writeToFile(std::vector<char>& buffer, int len, std::ofstream& out) {
    std::lock_guard<std::mutex> lock(mtx); // 加锁
    out.write(buffer.data(), len); // 写入文件
}

void readFile(std::ifstream& in, std::ofstream& out) {
    std::vector<char> buffer(BUFFER_SIZE);
    while (true) {
        int len = 0;
        {
            std::lock_guard<std::mutex> lock(mtx); // 加锁
            in.read(buffer.data(), BUFFER_SIZE); // 读取文件
            len = in.gcount();
        }
        if (len == 0) break; // 读取完毕
        writeToFile(buffer, len, out); // 写入文件
    }
}

int main() {
    std::ifstream in("input.txt", std::ios::binary);
    std::ofstream out("output.txt", std::ios::binary);

    std::vector<std::thread> threads;
    const int NUM_THREADS = 4; // 线程数
    for (int i = 0; i < NUM_THREADS; ++i) {
        threads.emplace_back(readFile, std::ref(in), std::ref(out)); // 创建线程
    }

    for (auto& thread : threads) {
        thread.join(); // 等待所有线程结束
    }

    in.close();
    out.close();
    return 0;
}

在这个示例中,我们使用了一个互斥锁来保证多个线程不会同时写入同一个文件。每个线程都会读取文件中的一部分数据,并将其写入到同一个文件中。线程数可以根据需要进行调整。在实际使用中,可以根据文件大小和系统资源等情况来确定最佳的线程数。

使用c++实现多线程同时读取一个大文件的数据并写入同一个文件

原文地址: https://www.cveoy.top/t/topic/gTy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录