用class对std::ofstream进行封装。
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
using namespace std;
class LogFile {
public:
LogFile() {
f.open("log.txt");
}
void shared_print(std::string id, int val) {
std::lock_guard<std::mutex> locker(m_mutex);
f << "From " << id << ": " << val << std::endl;
}
private:
std::mutex m_mutex;
// 该f不可暴露
std::ofstream f;
};
void func_1(LogFile& log) {
for (int i = 0; i > -100; --i) {
log.shared_print("from func_1 ", i);
}
}
class Fctor {
public:
void operator()(string& s) {
for (int i = 0; i > -10; --i) {
std::cout << "from t1: " << s << std::endl;
}
s = "factor";
}
};
int main() {
LogFile log;
std::thread t1(func_1, std::ref(log));
for (int i = 0; i < 100; ++i) {
log.shared_print("from main ", i);
}
t1.join();
return 0;
}
本文介绍了一个使用C++标准库中的std::ofstream来实现日志记录功能的简单封装类。通过创建一个名为LogFile的类,并利用std::mutex确保多线程环境下对文件的安全写入。该示例展示了如何在主线程和其他线程中同步地向日志文件中写入信息。
1973

被折叠的 条评论
为什么被折叠?



