本文主要是介绍c++多线程,adopt_lock_t/defer_lock_t/try_to_lock_t,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
std::adopt_lock_t
struct adopt_lock_t {};
constexpr adopt_lock_t adopt_lock {};
是一个空类,作为adopt_lock类型
对unique_lock or lock_guard的建造含糊,将adopt_lock作为参数传递,使object不要锁互斥量,并且假定互斥量已经被
当前线程锁住
std::defer_lock_t
struct defer_lock_t {};
是一个空类,used as the type of defer_lock
constexpr defer_lock_t defer_lock {};
对unique_lock的构造函数传递defer_lock,使它不要在构建阶段自动的锁定metex lock,
初始化对象as not owning a lock
std::try_to_lock_t
struct try_to_lock_t {};
是一个空类,used as the tyep of tyr_to_lock
constexpr try_to_lock_t try_to_lock {};
向unique_lock传递try_to_lock参数,使得它调用try_lock成员函数,而不是lock函数图lock the mutex object;
std::mutex foo, bar;void TaskA() {std::lock (foo, bar); //simultaneous lock prevent deadlockunique_lock<std::mutex> lck1(foo, std::adopt_lock);unique_lock<std::mutex> lck2 (bar, std::adopt_lock);std::cout<<"TaskA"<<std::endl;//unlock automatically on destruction of lck1, lck2;
}
void TaskB() { // foo.lock(); bar.lock();unique_lock<mutex> lck1, lck2;lck1 = unique_lock<mutex>(foo, std::defer_lock);lck2 = unique_lock<mutex> (bar, std::defer_lock);std::lock(lck1, lck2); // simultaneous lock prevent deadlockcout<<"TaskB"<<endl;
}
value | description |
---|---|
(no tag) | Lock on construction by calling member lock. |
try_to_lock | Attempt to lock on construction by calling member try_lock |
defer_lock | Do not lock on construction (and assume it is not already locked by thread) |
adopt_lock | Adopt current lock (assume it is already locked by thread). |
try_to_lock_t, defer_lock_t and adopt_lock_t are the types of objects try_to_lock, defer_lock and adopt_lock, respectively.
这篇关于c++多线程,adopt_lock_t/defer_lock_t/try_to_lock_t的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!