转自:https://www.youtube.com/watch?v=IBu5ka1MQ7w
unique_lock<mutex>、once_flag、call_once
// https://www.youtube.com/watch?v=IBu5ka1MQ7w
//Lazy Initialization
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<thread>
#include<mutex>
#include<string>
using namespace std;
class LogFile
{
public:
LogFile() {
//_f.open("log.txt");
};
~LogFile() {};
void share_print(string id,int val) {
//unique_lock<mutex> locker2(_mu_open);//_f只打开一次,但每个进程都要lock一下再判断,浪费时间!
//if (!_f.is_open()) {
// _f.open("log.txt");//Lazy Initialization
//}
call_once(_flag, [&]() {_f.open("log.txt"); });//只打开一次
//lock_guard<mutex> guard(_mu);
//unique_lock<mutex>比lock_guard<mutex>更加灵活,可以随时 lock()或者 unlock()
//unique_lock<mutex>可以移动(move)!!
unique_lock<mutex> locker(_mu,defer_lock);//defer_lock 延迟上锁!
//do somthing else
locker.lock();
_f << "From " <<id << ":" << val << endl;
locker.unlock();
/*locker.lock();
_f << "......:)..." << endl;
locker.unlock();*/
//unique_lock<mutex> locker2 = move(locker);
}
private:
mutex _mu;
mutex _mu_open;
ofstream _f;
once_flag _flag;
};
void thread_function(LogFile &log,string id,int val) {
log.share_print(id, val);
}
int main() {
LogFile log;
ofstream f;
f.open("log.txt");
f << "dsdads" << endl;
//log.share_print("main thread", 1);
thread t1(&thread_function ,ref(log), " thread 1", 1);
thread t2(&thread_function, ref(log), " thread 2", 2);
thread t3(&thread_function, ref(log), " thread 3", 3);
t1.join();
t2.join();
t3.join();
//getchar();
return 0;
}