Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have to link pthread when we use <thread> of C++11? [duplicate]

Tags:

c++

I want know why c++11 need link pthread? It look like just add some code to optimization pthread.

I want code a Cross-Platform c++ Program,as the same time it need using multithreading technology. In c++11, the look like support cross-platform, so I try it in ubuntu16.04, but in fact it still need link pthread when compile.

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

compile with "-std=c++0x -pthread" is ok. but if not add "-pthread" it will compile fail.

like image 902
shuyan Avatar asked Apr 04 '19 09:04

shuyan


1 Answers

C++11 defined standard classes, functions, memory model etc. to work with multiple threads. It doesn't concern how a particular compiler will provide the functionality. In case of Linux, gcc simply decided to use pthread library behind the scene and thats why we need to link with -pthread. Another environment or another compiler may not require this.

like image 167
taskinoor Avatar answered Oct 13 '22 17:10

taskinoor