爲什麼在std :: lock中沒有超時支持?
因爲沒有人提出它。
因爲這個領域如此有爭議,提議越少,越有可能被接受。
因爲我們害怕如果我們標準化所有東西,你會覺得無聊。
這是作爲讀者的練習。
嗯......我跑出來的想法... :-)
哦!
這是很容易,如果你需要它爲你做你自己:
更新
這裏有一個重寫我更喜歡:
#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);
}
安東尼建議,請隨時提出這個。也可以隨意使用它,並讓我們知道它是否真的有用。
'std :: lock'不是一個類型,[它是一個函數](http://en.cppreference.com/w/cpp/thread/lock)。 :) – Xeo
@Xeo:對,恩,謝謝。編輯。 – KnowItAllWannabe
@尼科爾:傳遞延期鎖有什麼問題? 'std :: lock'接受任何類型的可鎖定,你將不必擔心以後解鎖。 – Xeo