简体   繁体   中英

threading support in Clang++ 3.3 for C++11

the code at the bottom of this post compiles fine but generates an useless binary with

$ clang++ -v
clang version 3.3 (trunk 168461)
Target: x86_64-unknown-linux-gnu
Thread model: posix

when this command is given

clang++ -std=c++11 -pthread -s -O3 -DNDEBUG source.cpp -o source

the binary always generates this

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted (core dumped)

What I don't get is:

  • why i need to link the POSIX threads library if C++11 includes a threading model in the standard, why the flag -std=c++11 it's not enough ?
  • if clang++ supports -pthread or not, according to what I have read it should support pthreads

Thanks.


#include <iostream>
#include <thread>

void f()
{
  std::cout << "Hello World\n";
}

int main()
{
  std::thread t(f);
  t.join();
}

you should use the command like this:

clang++ -std=c++11 -pthread -stdlib=libstdc++ threadEx.cpp

You forgot to add the library. libc++ does not work for me with ubuntu 12.04, clang3.3 but I made it work with clang3.3 and g++ 4.7.2 (g++ 4.6.3 did not work either). Both works.

In thread.cc there is the following bit of code in thread::_M_start_thread():

if (!__gthread_active_p())
  __throw_system_error(int(errc::operation_not_permitted));

This is why it's blowing up for you --- libgcc checks for the existence of pthread_cancel() and only returns 1 if it exists. You didn't specify -pthread, so there's no pthread_cancel().

Why do you need to specify -pthread when building? I'm guessing it's because the alternative is to assume -pthread all the time and that causes unnecessary overhead.

Using the -pthread flag makes a huge difference when compiling the code, see gcc - significance of -pthread flag when compiling .

According to the accepted answer to the question What is g++'s -pthread equiv in clang? , clang supports -pthread .


Actually, this line you posted tells that you are using pthreads:

Thread model: posix

Pthreads won't go away , and I highly doubt that Clang / LLVM will implement a new threading library from scratch. Why would they? The platform's native library is mature enough.


Sorry, I cannot help you any further with this: I don't have clang installed on my machine, and your code runs just fine on my machine with gcc 4.6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM