What does atomic<>::load() mean by default ?
The load() operation performs a so-called acquire operation on the affected memory location, which by default ensures that all following memory operations, whether atomic or not, become visible to other threads after the load operation.
std::memory_order_seq_cst (sequential consistent memory order, by default)
std::memory_order_release
std::memory_order_acquire
std::memory_order_relaxed
5) Examples
#include <atomic> // for atomics
#include <future> // for async() and futures
#include <thread> // for this_thread
#include <chrono> // for durations
#include <iostream>
long data;
std::atomic<bool> readyFlag(false);
void provider ()
{
std::cout << "<return>" << std::endl;
std::cin.get();
data = 42;
// signal readiness
readyFlag.store(true);
}
void consumer ()
{
// wait for readiness and do something else
while (!readyFlag.load()) {
std::cout.put(’.’).flush();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "\nvalue : " << data << std::endl;
}
int main()
{
auto p = std::async(std::launch::async,provider);
auto c = std::async(std::launch::async,consumer);
}
Note: always should initialize atomic objects because the default constructor does not fully initialize it (it’s not that the initial value is undefined, it is that the lock is uninitialized).