15,471
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include<iostream>
#include <thread>
#include<mutex>
#include <string>
#include <fstream>
using namespace std;
class LofFile
{
public:
LofFile() {
f.oepn("log.txt");
}
void shared_print(string id, int value)
{
lock_guard<mutex>locker(m_mutex);
f << "from" << id << ":" << value << endl;
}
private:
mutex m_mutex;
std::ofstream f;
};
void function_1(LofFile&log) {
for (int i = 0; i > -100; i--)
log.shared_print("from ti:", i);
}
int main() {
LofFile log;
thread t1(function_1, ref(log));
for (int i = 0; i < 100; i++)
log.shared_print("from main", i);
t1.join();
}