lock_guard:创建时加锁,析构时解锁。
作用:为了防止在线程使用mutex加锁后异常退出导致死锁的问题,建议使用lock_guard代替mutex。
lock_guard的构造函数:
explicit lock_guard (mutex_type& m);
- lock_guard类通过在对象构造的时候对mutex进行加锁,当对象离开作用域时自动解锁,从而避免加锁后没有解锁的问题。
- lock_guard不能在中途解锁,只能通过析构时解锁。
- lock_guard对象不能被拷贝和移动。
test.cpp代码如下
#include
#include
#include
using namespace std;
int test_num = 0;
void testFunc(mutex& m)
{
for(int i = 0; i < 100; ++i)
{
lock_guard
test_num++;
}
cout << this_thread::get_id() << ":" << test_num << endl;
}
int main(){
mutex m;
thread t1(testFunc, ref(m));
thread t2(testFunc, ref(m));
t1.join();
t2.join();
cout<
}
编译:g++ test.cpp -o test -lpthread
运行:./test
结果:
140160548558592:200
140160540165888:200
200



