Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a std::pair containing a std::atomic?

I cannot figure out how to create the following:

std::pair<std::atomic<bool>, int>

I always invariably get

/usr/include/c++/5.5.0/bits/stl_pair.h:139:45: error: use of deleted function 'std::atomic::atomic(const std::atomic&)'
: first(__x), second(std::forward<_U2>(__y)) { }

I've tried

std::pair<std::atomic<bool>, int> pair = std::make_pair(true, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair({true}, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::atomic<bool>(true), 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::move(std::atomic<bool>(true)), 1); //doesn't work

I know std::atomic is non-copyable, so how are you supposed to create it in a pair? Is it just not possible?

like image 415
Rick D Avatar asked Mar 20 '19 21:03

Rick D


People also ask

What is std :: atomic in C++?

Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.

What is std :: pair?

std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.

How do you declare an atomic variable in C++?

In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.


1 Answers

You can do:

std::pair<std::atomic<bool>, int> p(true, 1);

This uses true to initialize the atomic first member, without any extraneous copies or moves. In C++17, guaranteed copy elision also allows you to write:

auto p = std::pair<std::atomic<bool>, int>(true, 1);
like image 154
Brian Bi Avatar answered Sep 27 '22 21:09

Brian Bi