std::recursive_mutex::try_lock

Tries to lock the mutex. Returns immediately. On successful lock acquisition returns true, otherwise returns false.

# Declarations

bool try_lock() noexcept;

(since C++11)

# Return value

true if the lock was acquired successfully, otherwise false.

# Example

#include <iostream>
#include <mutex>
 
int main()
{
    std::recursive_mutex test;
    if (test.try_lock())
    {
        std::cout << "lock acquired\n";
        test.unlock();
    }
    else
        std::cout << "lock not acquired\n";
 
    test.lock();
    // non-recursive mutex would return false from try_lock now
    if (test.try_lock())
    {
        std::cout << "lock acquired\n";
        test.unlock(); 
    }
    else
        std::cout << "lock not acquired\n";
 
    test.unlock();
}

# See also