名前空間
変種
操作

std::timed_mutex::try_lock_for

提供: cppreference.com
< cpp‎ | thread‎ | timed mutex
 
 
スレッドサポートライブラリ
スレッド
(C++11)
(C++20)
(C++20)
this_thread 名前空間
(C++11)
(C++11)
(C++11)
相互排他
(C++11)
汎用ロック管理
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
条件変数
(C++11)
セマフォ
ラッチとバリア
(C++20)
(C++20)
フューチャー
(C++11)
(C++11)
(C++11)
(C++11)
 
 
template< class Rep, class Period >
bool try_lock_for( const std::chrono::duration<Rep,Period>& timeout_duration );
(C++11以上)

ミューテックスのロックを試みます。 指定された timeout_duration が経過するか、ロックを取得するか、どちらかが先に発生するまでブロックします。 ロックの取得に成功した場合は true を返し、そうでなければ false を返します。

timeout_durationtimeout_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

[編集] 関連項目

ミューテックスをロックします。 利用可能でない場合はブロックします
(パブリックメンバ関数) [edit]
ミューテックスのロックを試みます。 利用可能でない場合はリターンします
(パブリックメンバ関数) [edit]
ミューテックスのロックを試みます。 指定された時刻に達するまでミューテックスが利用可能にならなければリターンします
(パブリックメンバ関数) [edit]
ミューテックスのロックを解除します
(パブリックメンバ関数) [edit]