This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: std::atomic<> for double


On Sat, 21 Apr 2012, niXman wrote:

where is a code that compiles and works as expected:
#include <atomic>
#include <iostream>

int main() {
  std::atomic<int> i(0);
  i += 3;

  std::cout << i << std::endl;
}
http://liveworkspace.org/code/eb92d1706687414dd3f49976584ff337

now change it to type double:
#include <atomic>
#include <iostream>

int main() {
  std::atomic<double> i(0);
  i += 3.14;

  std::cout << i << std::endl;
}
http://liveworkspace.org/code/555191936a23b06352220ff11b1e33df

and get the following error:
source.cpp: In function 'int main()':
source.cpp:6:9: error: no match for 'operator+=' in 'i += 3.1400000000000001e+0'

therefore, I have two questions: 1. Ñan double be actually an atomic type?

Yes, because it is trivially copyable.


2. how is supposed to use atomic <double> by standard?

double isn't an integral type, so you can't do much more than store, load, exchange and compare_exchange_{weak,strong}. For your case, you get the double value from the atomic, increment it, then use compare_exchange to store that new value in the atomic *if the atomic hasn't changed in the meantime*, and if the atomic has changed, try again. Note that the comparison is done with memcmp, not ==, which for double could be different.


example from the standard:

expected = current.load();
do {
  desired = function(expected);
} while (!current.compare_exchange_weak(expected, desired));


Note that there are already books available to learn these things, search for instance for "C++ Concurrency in Action".


--
Marc Glisse


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]