std::shared_timed_mutex::try_lock_for
template< class Rep, class Period > bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration ); |
(C++14以上) | |
ミューテックスのロックを試みます。 指定された timeout_duration が経過するか、ロックを取得するか、どちらかが先に発生するまでブロックします。 ロックの取得に成功した場合は true を返し、そうでなければ false を返します。
timeout_duration が timeout_duration.zero() より小さいまたは等しい場合、この関数は try_lock() のように動作します。
スケジューリングやリソースの奪い合いによる遅延のため、この関数は timeout_duration より長くブロックする可能性があります。
標準は時間計測に steady_clock を使用することを推奨しています。 処理系が代わりに system_clock を使用する場合、待機時間は時計調整の影響も受けるかもしれません。
try_lock() と同様に、この関数は timeout_duration の間のどこかの時点でミューテックスが他のいかなるスレッドにもロックされていなかったことがあっても、 spurious に失敗して false を返すことが認められています。
true を返した場合、同じミューテックスに対する以前の unlock() 操作は、この操作に対して同期します (std::memory_order を参照してください)。
いずれかのモード (共有または排他) でその mutex をすでに所有しているスレッドによって try_lock_for が呼ばれた場合、動作は未定義です。
引数
| timeout_duration | - | ブロックする最小時間 |
戻り値
ロックの取得に成功した場合は true、そうでなければ false。
例外
実行中に clock、time_point、または duration によって投げられるあらゆる例外 (標準ライブラリによって提供される clock、time_point、および duration は、例外を投げることはありません)。
例
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <sstream>
std::mutex cout_mutex; // control access to std::cout
std::timed_mutex mutex;
void job(int id)
{
using Ms = std::chrono::milliseconds;
std::ostringstream stream;
for (int i = 0; i < 3; ++i) {
if (mutex.try_lock_for(Ms(100))) {
stream << "success ";
std::this_thread::sleep_for(Ms(100));
mutex.unlock();
} else {
stream << "failed ";
}
std::this_thread::sleep_for(Ms(100));
}
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "[" << id << "] " << stream.str() << "\n";
}
int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i) {
threads.emplace_back(job, i);
}
for (auto& i: threads) {
i.join();
}
}
出力例:
[0] failed failed failed
[3] failed failed success
[2] failed success failed
[1] success failed success
関連項目
| ミューテックスをロックします。 利用可能でない場合はブロックします (パブリックメンバ関数) | |
| ミューテックスのロックを試みます。 利用可能でない場合はリターンします (パブリックメンバ関数) | |
| ミューテックスのロックを試みます。 指定された時刻に達するまでミューテックスが利用可能にならなければリターンします (パブリックメンバ関数) | |
| ミューテックスのロックを解除します (パブリックメンバ関数) |