A Guide to std::try_lock in C++: Common Problems and Better Alternatives

2025-09-18

std::try_lock is a function that tries to acquire a lock on multiple mutexes at the same time without blocking. Unlike std::lock, which will block indefinitely until it can acquire all the locks, std::try_lock is non-blocking. It's especially useful for avoiding deadlocks when you need to lock several mutexes simultaneously.

The function returns a -1 if it successfully acquires all the locks. If it fails to lock even one mutex, it immediately unlocks all the mutexes it had previously acquired and returns the zero-based index of the mutex it failed to lock.

Here are a few common issues developers run into with std::try_lock and how to handle them.

A frequent mistake is not checking the return value correctly. People often forget that std::try_lock returns an index, not just a simple boolean.

Problematic Code

// This is an oversimplified example and not good practice
// Don't do this!
std::mutex m1, m2;
if (std::try_lock(m1, m2) == 0) {
    // This logic is incorrect. The value 0 means it failed to lock m2.
    // The programmer might think 0 means success.
    // ...
}

Correct Approach
You must check for the successful return value, which is -1.

std::mutex m1, m2;
int lock_result = std::try_lock(m1, m2);
if (lock_result == -1) {
    // Success! Acquired both locks.
    // Now you can safely access shared resources.
    // Don't forget to use std::unique_lock or std::lock_guard
    // to manage the locks automatically.
    std::unique_lock<std::mutex> lk1(m1, std::adopt_lock);
    std::unique_lock<std::mutex> lk2(m2, std::adopt_lock);
    // ... your critical section code ...
} else {
    // Failed to acquire all locks.
    // The value of 'lock_result' tells you which mutex failed.
    // You can handle the failure here.
    // For example, you might try again later or log the failure.
    // It's often better to just re-try in a loop.
}

Explanation
When you get a -1, it's all good. If you get any other number, it means the lock failed and you need to handle that. A common strategy is to re-try the lock acquisition in a loop until it succeeds.

Sometimes, std::try_lock might not be the best fit for your situation. Here are two excellent alternatives.

For simply locking multiple mutexes at once, std::scoped_lock is often a better and safer choice. It guarantees that all locks are acquired without a deadlock, and it's exception-safe. The downside is that it is a blocking function. It will wait until it can acquire all the locks.

When to use it
When you need to lock multiple mutexes and you are okay with blocking until all locks are acquired. It's the simplest and safest way to avoid deadlocks.

Example

std::mutex m1, m2;

void transfer(int amount) {
    // std::scoped_lock locks both mutexes in a deadlock-free way
    // The locks are automatically released when the function exits
    // No need for try-catch or manual unlocking!
    std::scoped_lock lock(m1, m2); 
    // ... your critical section code ...
    // The locks are released automatically when the lock object goes out of scope.
}

Why it's better
It's more concise and handles the locking and unlocking automatically. You don't have to worry about the return value or manually releasing locks on failure. It uses a clever algorithm to prevent deadlocks, similar to std::lock.

If you really need a non-blocking lock and want more flexibility, you can use std::unique_lock with the std::try_to_lock deferring tag. This approach gives you more control over a single lock.

When to use it
When you need a non-blocking lock on a single mutex and want the flexibility of std::unique_lock, such as deferred locking or timed locking.

Example

std::mutex m1;

void do_something_if_not_busy() {
    std::unique_lock<std::mutex> lk(m1, std::try_to_lock);
    
    // Check if the lock was acquired
    if (lk.owns_lock()) {
        // Success! Acquired the lock.
        // ... your critical section code ...
        // Lock is released automatically when lk goes out of scope.
    } else {
        // Lock was not acquired.
        // You can do other work here instead of waiting.
        // ...
    }
}

Why it's useful
It's great when your thread has other tasks it can do if it can't acquire the lock immediately. It prevents the thread from being blocked, which can improve the overall responsiveness of your program.


cpp



The sizeof... Operator in C++: Common Pitfalls and Alternatives

A frequent problem people run into is trying to use sizeof. .. on something that isn't a parameter pack. This will lead to a compilation error


Lock-Free Programming in C++: Understanding Hazard Pointers and std::shared_ptr as an Alternative

In lock-free programming, you often have a situation where one thread is removing a node from a data structure while another thread is trying to read from it


Common Pitfalls of std::basic_ios::swap and How to Avoid Them

std::basic_ios::swap is a member function that swaps all internal state of two basic_ios objects, like std::ios or std::fstream



The Secret Key: Using std::locale::id for C++ Localization Extension

The std::locale::id class is a private, non-copyable type that acts as a unique index or identifier for a specific type of locale facet


The Ins and Outs of C++ std::chrono::year Decrement

The std::chrono::year::operator-- decrements a std::chrono::year object by one year. There are two versions the pre-decrement (--year) and the post-decrement (year--)


Mastering C++ Loops: A Guide to 'continue' and Its Pitfalls

The continue statement is a control flow statement used inside loops (like for, while, and do-while). When the program encounters a continue statement


Safe Multithreading with std::shared_ptr: Atomic Operations vs. Mutexes

In C++, std::shared_ptr is a smart pointer that manages a shared resource. It handles memory automatically, which is great


Troubleshooting std::subtract_with_carry_engine in C++: Common Issues and Alternatives

The std::subtract_with_carry_engine is a type of pseudo-random number generator (PRNG) in C++. Think of it as a tool that creates a sequence of numbers that looks random


Applying Arctangent to std::valarray: A Guide to std::atan and Its Alternatives

The std::atan function for std::valarray is designed to apply the arctangent operation to each element of the array. However


C++ Scope: A Friendly Guide to Avoiding Pitfalls

One of the most frequent issues is when a variable in an inner scope "shadows" or hides a variable with the same name in an outer scope