0

Consider this simple code:

#include <iostream>
#include <atomic>

void add(std::atomic<double> & a, double c)
{
    std::atomic_fetch_add(&a, c);
}

int main()
{
    std::atomic<double> a;

    a.store(0);
    std::cout << a.load() << std::endl;

    add(a, 5.0);
    std::cout << a.load() << std::endl;

    std::cin.get();
}

Compiling it will result in:

error LNK2019: unresolved external symbol "double __cdecl std::atomic_fetch_add(struct std::atomic *,double)" (??$atomic_fetch_add@N@std@@YANPAU?$atomic@N@0@N@Z) referenced in function "void __cdecl add(struct std::atomic &,double)" (?add@@YAXAAU?$atomic@N@std@@N@Z)

According to this, atomic_fetch_add is defined in <atomic>, so what is happening?

Jaber
  • 17
  • 6
  • Who told you that `std::atomic` is specialized for `double`? – Slava Jun 14 '17 at 13:43
  • It is, but [none of the overloads take a double](http://en.cppreference.com/w/cpp/atomic/atomic_fetch_add) – Borgleader Jun 14 '17 at 13:47
  • @Slava I didn't see anywhere that I can't use it for `double`! – Jaber Jun 14 '17 at 13:47
  • @Jaber http://en.cppreference.com/w/cpp/atomic/atomic - types explicitly listed for which `std::atomic` is fully or partially specialized, `double` is not in the list. – Slava Jun 14 '17 at 13:54

1 Answers1

1

As stated in documentation:

The standard library provides specializations of the std::atomic template for the following types:

and double is not in the list. There is also note for non member functions:

There are non-member function template equivalents for all member functions of std::atomic. Those non-member functions may be additionally overloaded for types that are not specializations of std::atomic, but are able to guarantee atomicity. The only such type in the standard library is std::shared_ptr.

So double is not supported.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • Do you know any library which implemented atomic arithmetic for non-integral types? – Jaber Jun 14 '17 at 14:09
  • 1
    @Jaber, no never needed such beast, I use mutex - premature optimization is root of all evil. – Slava Jun 14 '17 at 14:14
  • 2
    to clarify your answer: `double` is supported for basic atomic operations like (`load`, `store`, etc); but isn't supported for specialized operations (like arithmetic `+`, `-`, ...) as stated [here](https://stackoverflow.com/questions/30048533/why-isnt-atomic-double-fully-implemented/30050429#30050429). – Jaber Jun 14 '17 at 14:27