Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ thread-local storage clang-503.0.40 (Mac OSX)

After I declared a variable in this way:

   #include <thread>
   namespace thread_space
    {
    thread_local int s;
    } //etc.

i tried to compile my code using 'g++ -std=c++0x -pthread [sourcefile]'. I get the following error:

example.C:6:8: error: thread-local storage is unsupported for the current target
static thread_local int s;
       ^
1 error generated.

If i try to compile the same code on Linux with GCC 4.8.1 whit the same flags, i get a functioning executable file. I'm using clang-503.0.40 (the one which comes with Xcode 5.1.1) on a MacBook Pro running OSX 10.9.3. Can anybody explain me what i'm doing wrong? Thank you!!

like image 339
pier94 Avatar asked May 21 '14 18:05

pier94


3 Answers

Try clang++ -stdlib=libc++ -std=c++11. OS X's outdated libstdc++ doesn't support TLS.

Edit

Ok, this works for the normal clang version but not for the Xcode one.

I did a diff against Apple's clang (503.0.38) and the normal released one and found the following difference:

        .Case("cxx_thread_local",
-                 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported() &&
-                 !PP.getTargetInfo().getTriple().isOSDarwin())
+                 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())

So I think this is a bug in Apple's clang version (or they kept it in there on purpose - but still weird, because -v says based on 3.4).

like image 133
Thomas Avatar answered Nov 07 '22 04:11

Thomas


Alternatively, you can use compiler extensions such as __thread (GCC/Clang) or __declspec(thread) (Visual Studio).

Wrap it in a macro and you can easily port your code across different compilers and language versions:

#if HAS_CXX11_THREAD_LOCAL
    #define ATTRIBUTE_TLS thread_local
#elif defined (__GNUC__)
    #define ATTRIBUTE_TLS __thread
#elif defined (_MSC_VER)
    #define ATTRIBUTE_TLS __declspec(thread)
#else // !C++11 && !__GNUC__ && !_MSC_VER
    #error "Define a thread local storage qualifier for your compiler/platform!"
#endif

...

ATTRIBUTE_TLS static unsigned int tls_int;
like image 3
glampert Avatar answered Nov 07 '22 05:11

glampert


The clang compiler included in the Xcode 8 Beta and GM releases supports the C++11 thread_local keyword with both -std=c++11 and -std=c++14 (as well as the GCC variants).

Earlier versions of Xcode apparently supported C-style thread local storage using the keywords __thread or _Thread_local, according to the WWDC 2016 video "What's New in LLVM" (see the discussion beginning at 5:50).

like image 2
rsfinn Avatar answered Nov 07 '22 05:11

rsfinn