C++ Atomic::is_lock_free() function



The C++ std::atomic::is_lock_free() function is used to check whether the operations on the specific atomic type are lock-free, meaning they do not use locks for synchronization. Lock-free operations ensures that the program does not get stuck by other threads. The function returns true if the atomic operations on the object is lock-free otherwise it return false.

Syntax

Following is the syntax for std::atomic::is_lock_free() function.

bool is_lock_free() const volatile noexcept;
bool is_lock_free() const noexcept;

Parameters

It does not accepts any parameter.

Return Value

It returns true if the atomic operations on the objects of this type are lock-free, false otherwise.

Exceptions

This function never throws exceptions.

Example

In the following example, we are going to consider the basic usage of the is_lock_free() function.

#include <atomic>
#include <iostream>
int main()
{
    std::atomic<int> x;
    bool lockFree = x.is_lock_free();
    std::cout << "Is atomic int lock-free? " << std::boolalpha << lockFree << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Is atomic int lock-free? true

Example

Consider the following example, where we are going to check whether atomic<bool> is lock free or not.

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<bool> a;
    if (a.is_lock_free()) {
        std::cout << "It is lock-free." << std::endl;
    } else {
        std::cout << "It is not lock-free." << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

It is lock-free.
atomic.htm
Advertisements