c++ - How to perform basic operations with std::atomic when the type is not Integral? -
to precise, need increase double double , want thread safe. don't want use mutex since execution speed dramatically decrease.
as rule, c++ standard library tries provide operations can implemented efficiently. std::atomic, means operations can performed lock-free in instruction or 2 on "common" architectures. "common" architectures have atomic fetch-and-add instructions integers, not floating point types.
if want implement math operations atomic floating point types, you'll have cas (compare , swap) loop (live @ coliru):
std::atomic<double> foo{0}; void add_to_foo(double bar) { auto current = foo.load(); while (!foo.compare_exchange_weak(current, current + bar)) ; }
Comments
Post a Comment