2

给定一个使用 C++11 线程特性的简单程序:

#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();
}

如果我使用以下方法构建应用程序:

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

该程序构建良好,但是当我运行它时,我得到:

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

如果我用-pthread如下方式构建它:

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

该程序执行良好。我还没有看到任何其他需要特殊构建标志的 C++11 功能,为什么会有这个?

4

1 回答 1

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.

于 2013-10-11T15:28:48.763 回答