2

Given a simple program that uses C++11 threading features:

#include <iostream>
#include <thread>

using namespace std;

void dont_thread_on_me() {
    cout << "action from another thread" << endl;
}

int main() {
    thread t { dont_thread_on_me };
    t.detach();

    cin.get();
}

If I build the application using:

c++ -std=c++11 Program.cpp -o Program.out

the program builds fine, but when I run it, I get:

./Program.out
terminate called after throwing an instance of 'std::system_error'
   what():  Operation not permitted
Aborted

If I build it with -pthread as in:

c++ -std=c++11 Program.cpp -o Program.out -pthread

the program executes fine. I haven't seen any other C++11 features that require special build flags, why does this one?

sircodesalot
  • 11,231
  • 8
  • 50
  • 83

1 Answers1

2

The Operation not permitted exception is thrown in a function called _M_start_thread defined in gcc-4.7.3/libstdc++-v3/src/c++11/thread.cc.

This exception is thrown if a function called __gthread_active_p returns a null value. This function is a C function defined in gcc-4.7.3/libgcc/gthr-posix.h.

This method pokes around in libc for the pthread functions and presumably does some funky runtime/lazy binding. Your C++ code links without problem because it doesn't contain any link-time dependency on pthread. C code can tolerate missing link values for functions which it will try to resolve at runtime.

Unfortunately, the C++ sanity checks we normally depend on to catch these issues are bypassed because the pthread linking is done via lazy binding in C code.

Gearoid Murphy
  • 11,834
  • 17
  • 68
  • 86