C++11之 unique_lock和lock_guard避免死锁
标签:mes ios stream 性能 join() unique eth provided cal
#include
#include
#include
#include
#include string>
using namespace std;
class LogFile {
public:
LogFile() {
f.open("log.txt");
}
~LogFile() {
}
void shared_print(string msg, int id) {
lock_guard guard(mu);
fendl;
}
// Never return f to the outside world
ofstream& getStream() { return f;}
// Never pass f as an augument to user provided function
void processf(void fun(ofstream&)) {
fun(f);
}
private:
ofstream f;
mutex mu;
};
void function_1(LogFile& log) {
for(int i = 0; i >-100; i--) {
log.shared_print("From t1: ",i);
}
}
int main()
{
LogFile log;
thread t1(function_1,ref(log));
for(int i= 0; i 100; i++) {
log.shared_print("From main: ",i);
}
t1.join();
return 0;
}
当需要同时申请多把锁的时候,使用如下两种方式
lock(mtx1,mtx2)
lock_guard(mtx1,adopt_lock)
lock_guard(mtx2,adopt_lock)
unique_lock lock1(mtx1,defer_lock)
unique_lock lock2(mtx2,defer_lock)
lock(lock1,lock2)
unique_lock VS lock_guard
lock_guard 不允许手动unlock/lock 性能消耗小
unique_lock更加灵活, 允许手动多次 unlock/lock 性能消耗大
void foo() {
unique_lock locker(mtx,defer_lock); defer_lock假定还没有上锁
// do something not using mtx
mtx.lock();
// do something using mtx to protect
mtx.unlock();
// do something else
}
Lazy Initialization
#include
#include
#include
#include
#include string>
using namespace std;
class LogFile {
private:
ofstream f;
mutex _mu;
mutex _mu_open;
public:
void shared_print(string& msg, int id) {
{
unique_lock open_lck(_mu_open);
if(!f.is_open()) {
f.open("log.txt");
}
}
unique_lock locker(_mu);
// do other things
}
};
class LazyInitializationLogFile {
private:
ofstream f;
mutex _mu;
once_flag _flag;
public:
void shared_print(string7 msg, int id) {
call_once(_flag,[&](){f.open("log.txt");});
unique_lock locker(_mu);
// do other things
}
}
int main()
{
return 0;
}
C++11之 unique_lock和lock_guard避免死锁
标签:mes ios stream 性能 join() unique eth provided cal
原文地址:https://www.cnblogs.com/bitsstitcher/p/11532619.html
评论