在 Linux 中构建 C++11 个可线程翻译单元

Building C++11 threadable translation-units in linux

本文关键字:线程 翻译 单元 C++11 Linux 构建      更新时间:2023-10-16

给定一个使用 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 功能,为什么这个?

Operation not permitted异常是在 gcc-4.7.3/libstdc++-v3/src/c++11/thread.cc 中定义的名为 _M_start_thread 的函数中引发的。

如果名为 __gthread_active_p 的函数返回 null 值,则会引发此异常。此函数是 gcc-4.7.3/libgcc/gthr-posix.h 中定义的C函数。

此方法在 pthread 函数的libc中四处闲逛,并且可能执行一些时髦的运行时/懒惰绑定。您的C++代码链接没有问题,因为它不包含对 pthread 的任何链接时间依赖。C 代码可以容忍它将在运行时尝试解析的函数缺少链接值。

不幸的是,我们通常用来捕获这些问题的C++健全性检查被绕过了,因为 pthread 链接是通过 C 代码中的惰性绑定完成的。