C++ Atomic::load() function



The C++ std::atomic::load() function is used to retrieve the current value without performing any modifications. It provides a synchronized read operation that provides consistency in multi threaded environments, preventing data races and ensuring that the retrieved reflects the recent modification.

Syntax

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

T load (memory_order sync = memory_order_seq_cst) const volatile noexcept;
T load (memory_order sync = memory_order_seq_cst) const noexcept;

Parameters

  • sync − It indicates the synchronization mode for the operation.

Return Value

It returns the current value of the atomic variable.

Exceptions

This member function never throws exceptions.

Example

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

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(12);
    int a = x.load();
    std::cout << "Value: " << a << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Value: 12

Example

Consider the following example, where we are going to use std::memory_order_acquire as an argument to the load() function.

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<char> x('A');
    char a = x.load(std::memory_order_acquire);
    std::cout << "Value: " << a << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Value: A
atomic.htm
Advertisements