Namespaces
Variants

std::unique_lock<Mutex>:: try_lock

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
bool try_lock ( ) ;
(C++11以降)

関連するミューテックスのロックを(つまり所有権を取得)ブロックせずに試みます。実質的に mutex ( ) - > try_lock ( ) を呼び出します。

std::system_error は、関連付けられたミューテックスが存在しない場合、またはミューテックスが既にこの std::unique_lock によってロックされている場合にスローされます。

目次

パラメータ

(なし)

戻り値

true ミューテックスの所有権が正常に取得された場合、 false それ以外の場合。

例外

  • mutex ( ) - > try_lock ( ) によってスローされる例外( Mutex 型は try_lock で例外をスローしないが、カスタム Lockable はスローする可能性がある)。

以下の例は、ロックおよびアンロックされたミューテックスの取得を試みます。

#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
using namespace std::chrono_literals;
int main()
{
    std::mutex counter_mutex;
    std::vector<std::thread> threads;
    using Id = int;
    auto worker_task = [&](Id id, std::chrono::seconds wait, std::chrono::seconds acquire)
    {
        // wait for a few seconds before acquiring lock.
        std::this_thread::sleep_for(wait);
        std::unique_lock<std::mutex> lock(counter_mutex, std::defer_lock);
        if (lock.try_lock())
            std::cout << '#' << id << ", lock acquired.\n";
        else
        {
            std::cout << '#' << id << ", failed acquiring lock.\n";
            return;
        }
        // keep the lock for a while.
        std::this_thread::sleep_for(acquire);
        std::cout << '#' << id << ", releasing lock (via destructor).\n";
    };
    threads.emplace_back(worker_task, Id{0}, 0s, 2s);
    threads.emplace_back(worker_task, Id{1}, 1s, 0s);
    threads.emplace_back(worker_task, Id{2}, 3s, 0s);
    for (auto& thread : threads)
        thread.join();
}

出力:

#0, lock acquired.
#1, failed acquiring lock.
#0, releasing lock (via destructor).
#2, lock acquired.
#2, releasing lock (via destructor).

関連項目

関連付けられたミューテックスのロックを取得(所有権を取得)
(public member function)
関連付けられた TimedLockable ミューテックスのロックを試行(所有権を取得)、指定された時間ミューテックスが利用できない場合は制御を返す
(public member function)
関連付けられた TimedLockable ミューテックスのロックを試行(所有権を取得)、指定された時点までミューテックスが利用できない場合は制御を返す
(public member function)
関連付けられたミューテックスのロックを解除(所有権を解放)
(public member function)