用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;
}