0

I am trying to adapt my program to use long double instead of double, in which I also use atomic numbers.

After the change I encountered something that looks like an infinite cycle in the std::atomic library.

Here is a sample code to illustrate the problem:

    #include <atomic>
    #include <iostream>

    std::atomic<long double> my_long;

    int main(){

      long double my_temp = my_long;

      while (!my_long.compare_exchange_weak(my_temp, my_temp + 5.0L)) {
          my_temp = my_long;
      }

      std::cout << "Finished!" << std::endl;
      return 0;
    }

Now using atomic with types of non-standard sizes require to link against the atomic library, so the compile/link is successful, but the execution seems to be in an infinite cycle:

user@comp:/usr$ g++ atomic_test.cpp -latomic -std=c++14
user@comp:/usr$ ./a.out
^C

If the variable type is replaced from long double to double, there is no block, and the program executes as intended.

user@comp:/usr$ g++ atomic_test.cpp -latomic -std=c++14
user@comp:/usr$ ./a.out
Finished!

Why does this happen?


g++ version:

user@comp:/usr$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/6/lto-wrapper
Target: x86_64-linux-gnu
...
linux-gnu
Thread model: posix
gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
selbie
  • 100,020
  • 15
  • 103
  • 173
Dávid Tóth
  • 2,788
  • 1
  • 21
  • 46
  • how it even links? all gcc versions I tried end up with link error that functions for atomic exchange aren't found – Swift - Friday Pie Mar 06 '20 at 07:54
  • you have to link against -latomic explicitly – Dávid Tóth Mar 06 '20 at 07:57
  • Could be a bug. Works with version 9.1 of GCC (as seen e.g. [here](https://godbolt.org/z/hhEA92)). – Some programmer dude Mar 06 '20 at 07:59
  • nothing below 9.1 work there. perhaps something to do with no guarantee to support 16-byte values – Swift - Friday Pie Mar 06 '20 at 08:06
  • Gentleman, I can't emphasize how grateful I am, that you tested this with the latest version! Would someone be kind enough to write an answer, that above gcc 9.1 this is no longer an issue? Thank you! – Dávid Tóth Mar 06 '20 at 15:29
  • 2
    On a somewhat related note: check `std::atomic::is_lock_free`. My guess is that it's false, and operations on `std::atomic` use a mutex internally. In that case, switching from `std::atomic` to `std::atomic` may have substantially altered your program's performance profile. – Igor Tandetnik Mar 08 '20 at 04:15

0 Answers0