6

I encounter this compiler error

function std::atomic::is_lock_free() const: error: undefined reference 
to '__atomic_is_lock_free' 

when compiling code like below using gcc 4.7.2 on linux.

struct S {
  int a;
  int b;
};


  std::atomic<S> s;
  cout << s.is_lock_free() << endl;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Derek
  • 557
  • 1
  • 4
  • 16
  • Unlikely to make you happy, but: It seems to work on gcc 4.8 and ICC 13. – us2012 Mar 04 '13 at 14:49
  • @us2012 is `std::atomic` on user-defined POD types standard or a GCC extension? [cppreference](http://en.cppreference.com/w/cpp/atomic/atomic) only says that "full specializations" define atomic types and that "the following full specializations are provided" – Stephen Lin Mar 04 '13 at 14:51
  • @Stephen - There is a generic `atomic` in the standard (requiring T to be trivially copyable). Its `is_lock_free()` should likely return `false` and not use the compiler intrinsic. – Bo Persson Mar 04 '13 at 15:04
  • @BoPersson ok, I think someone needs to update cppreference then, it doesn't mention anything about that or the requirement of `T` being trivially copyable – Stephen Lin Mar 04 '13 at 15:07
  • 3
    @BoPersson - if the type `T` is small enough to be handled with hardware atomic instructions (typically no larger than the largest integral type) `atomic` can be lock free. – Pete Becker Mar 04 '13 at 15:52
  • I ran into this exact situation on an embedded ARM linux codebase using gcc 4.7.3. As a workaround, I'm currently wrapping a struct like yours in a union with a 64 bit int to enforce the behavior I want, and it turns out that is_lock_free() is provided for workaround. – notlesh Jul 20 '15 at 19:26
  • The result looks something similar to: union Foo { long long int s; struct S { int a; int b;}}; – notlesh Jul 20 '15 at 19:27

1 Answers1

11

Atomic API isn't complete in GCC 4.7:

  • When lock free instructions are not available (either through hardware or OS support) atomic operations are left as function calls to be resolved by a library. Due to time constraints and an API which is not finalized, there is no libatomic supplied with GCC 4.7. This is easily determined by encountering unsatisfied external symbols beginning with __atomic_*.

Since there is no libatomic shipped with GCC 4.7 you need to use another compiler which actually supports the features you want or provide the missing features (sample implementation).

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 6
    Well, the gcc guys provide a sample implementation of libatomic in a single file, in a link just one paragraph below the one you quoted: http://gcc.gnu.org/wiki/Atomic/GCCMM?action=AttachFile&do=view&target=libatomic.c It can be compiled and linked with programs that otherwise fail to compile with gcc4.7. (No idea how efficient or correct this implementation is, though.) – us2012 Mar 04 '13 at 15:11