以下是一个使用原子变量读写文件的C++示例代码:

#include <iostream>
#include <fstream>
#include <atomic>
#include <string>

int main() {
    std::ofstream file("data.txt");
    file << "Hello, World!";
    file.close();

    std::string content;
    std::atomic<bool> isReading(false);

    // 读文件线程
    std::thread readThread([&]() {
        while (isReading.load()) {
            std::ifstream file("data.txt");
            if (file.is_open()) {
                std::string line;
                std::getline(file, line);
                content = line;
                file.close();
            }
        }
    });

    // 写文件线程
    std::thread writeThread([&]() {
        isReading.store(true);
        std::ofstream file("data.txt", std::ios::trunc);
        if (file.is_open()) {
            file << "Hello, C++!";
            file.close();
        }
        isReading.store(false);
    });

    writeThread.join();
    readThread.join();

    std::cout << "File content: " << content << std::endl;

    return 0;
}

在上述代码中,我们使用std::atomic<bool>类型的变量isReading来控制读写文件的同步。isReading变量的初始值为false,当写文件线程开始写入文件时,将其设置为true,表示正在读取文件。读文件线程会持续尝试打开文件并读取文件内容,直到isReading变量变为false时停止。写文件线程会在写入文件前将isReading变量设置为true,然后写入文件完成后再将其设置为false

该示例中,写文件线程将文件内容修改为"Hello, C++!",读文件线程在写入完成后读取文件内容,并将其存储在content变量中。最后,我们将content变量的值输出到控制台。

请注意,这仅是一个简单的示例,实际应用中可能需要更复杂的读写逻辑和更严格的同步机制。

c++举一个用原子变量读写文件的例子

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

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