建设视频网站需要什么知识,一流的山西网站建设,网站建设风险管理,中国万网提供的服务和收费情况lock_guard
锁守卫是一个管理mutex对象的对象#xff0c;使其始终处于锁定状态。在构造时#xff0c;mutex对象被调用线程锁定#xff0c;在销毁时#xff0c;mutex被解锁。这是最简单的锁#xff0c;作为一个自动持续时间的对象#xff0c;它的作用特别大#xff0c;可…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_errorstd::mutex mtx;void print_even (int x) {if (x%20) 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_guardstd::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 i0; i10; i)threads[i] std::thread(print_thread_id,i1);for (auto th : threads) th.join();return 0;
}
参考链接
lock_guard