2012-09-24 20 views
9

如果我想抓住多個鎖不運行死鎖的風險,我可以使用std::lock功能:爲什麼在std :: lock中不支持超時?

int data1, data2; 
std::mutex m1, m2; 
std::unique_lock<std::mutex> lock1(m1, std::defer_lock); 
std::unique_lock<std::mutex> lock2(m2, std::defer_lock); 

std::lock(lock1, lock2);   // guaranteed deadlock-free 

// work with data1 and data2 

但是,如果我想在指定的時間和超時否則內獲取的鎖呢?對於期貨和條件變量,類似wait_until的鎖有沒有像try_until這樣的理由?

+0

'std :: lock'不是一個類型,[它是一個函數](http://en.cppreference.com/w/cpp/thread/lock)。 :) – Xeo

+0

@Xeo:對,恩,謝謝。編輯。 – KnowItAllWannabe

+0

@尼科爾:傳遞延期鎖有什麼問題? 'std :: lock'接受任何類型的可鎖定,你將不必擔心以後解鎖。 – Xeo

回答

11

爲什麼在std :: lock中沒有超時支持?

  1. 因爲沒有人提出它。

  2. 因爲這個領域如此有爭議,提議越少,越有可能被接受。

  3. 因爲我們害怕如果我們標準化所有東西,你會覺得無聊。

  4. 這是作爲讀者的練習。

嗯......我跑出來的想法... :-)

哦!

這是很容易,如果你需要它爲你做你自己:

更新

這裏有一個重寫我更喜歡:

#include <mutex> 
#include <chrono> 

template <class Clock, class Duration, class L0, class L1> 
int 
try_lock_until(std::chrono::time_point<Clock, Duration> t, L0& l0, L1& l1) 
{ 
    std::unique_lock<L0> u0(l0, t); 
    if (u0.owns_lock()) 
    { 
     if (l1.try_lock_until(t)) 
     { 
      u0.release(); 
      return -1; 
     } 
     else 
      return 1; 
    } 
    return 0; 
} 

template <class Rep, class Period, class L0, class L1> 
int 
try_lock_for(std::chrono::duration<Rep, Period> d, L0& l0, L1& l1) 
{ 
    return try_lock_until(std::chrono::steady_clock::now() + d, l0, l1); 
} 


int main() 
{ 
    std::timed_mutex m1, m2; 
    try_lock_for(std::chrono::milliseconds(50), m1, m2); 
} 

安東尼建議,請隨時提出這個。也可以隨意使用它,並讓我們知道它是否真的有用。

10

std::timed_mutextry_lock_untiltry_lock_for成員函數。然而,你是對的,沒有相當於std::lock超時。

使用超時鎖定互斥鎖僅適用於特定的壁龕。用超時鎖定多個互斥鎖並不是任何人都足夠強烈的建議,所以它不在C++ 11中。

標準委員會目前正在積極尋求下一個標準的提案。如果您覺得支持超時的std::lock等價物很有價值,那麼爲什麼不寫一個建議呢?

相關問題