为什么使用C ++ 11的<thread>时必须链接pthread?

时间:2019-04-04 09:50:27

标签: c++

我想知道为什么c ++ 11需要链接pthread?看起来只需向优化pthread添加一些代码即可。

我想编写一个跨平台的c ++程序,同时需要使用多线程技术。在c ++ 11中,外观看起来像是支持跨平台的,因此我在ubuntu16.04中进行了尝试,但实际上,编译时它仍然需要链接pthread。

#include <thread>
#include <functional>

namespace thread_test{
    void test_thread_1(int & i_flag);
    void test_thread_2(int & i_flag);
}

int main(int arc, char ** argv){
    int i_flag_1 = 0;
    int i_flag_2 = 1;
    std::thread thread_test_0();
    std::thread thread_test_1(thread_test::test_thread_1, std::ref(i_flag_1));
    std::thread thread_test_2(thread_test::test_thread_2, std::ref(i_flag_2));
    thread_test_1.join();
    thread_test_2.join();
    return 0;
}
void thread_test::test_thread_1(int & i_flag){
    i_flag = i_flag ? 0 : 1;
}
void thread_test::test_thread_2(int & i_flag){
    i_flag = i_flag ? 0 : 1;
}

使用“ -std = c ++ 0x -pthread”进行编译是可以的。 但是,如果不添加“ -pthread”,它将编译失败。

1 个答案:

答案 0 :(得分:0)

C ++ 11定义了可与多个线程一起使用的标准类,函数,内存模型等。它与特定的编译器将如何提供功能无关。对于Linux,gcc只是决定在后台使用pthread库,这就是为什么我们需要与-pthread链接。另一个环境或另一个编译器可能不需要这样做。

相关问题