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 deadlock
    unique_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 deadlock
    cout<<"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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章