lock_guard
- 锁守卫是一个管理mutex对象的对象,使其始终处于锁定状态。
- 在构造时,mutex对象被调用线程锁定,在销毁时,mutex被解锁。这是最简单的锁,作为一个自动持续时间的对象,它的作用特别大,可以持续到上下文结束。通过这种方式,它可以保证mutex对象在发生异常时被正确解锁。
- 但请注意,lock_guard对象并不以任何方式管理mutex对象的寿命:mutex对象的持续时间至少应延长到锁定它的lock_guard被破坏为止。
代码
// lock_guard example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error
std::mutex mtx;
void print_even (int x) {
if (x%2==0) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
}
void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (mtx);
print_even(id);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
参考链接