Why is -pthread necessary for usage of std::thread in GCC and Clang?

后端 未结 1 2031
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 01:22

Why does specifying -std=c++11 when compiling a program that directly or indirectly uses std::thread not imply -pthread? It seems stra

相关标签:
1条回答
  • 2020-12-07 02:01

    The -pthread option is not universally required to use std::thread - it's an implementation quirk of whatever platform you're building on.

    Compiling:

    #include <thread>
    #include <iostream>
    
    int main()
    {
        std::thread t{[]()
            {
                std::cout << "Hello World\n";
            }};
        t.join();
        return 0;
    }
    

    with

    clang -std=c++11 ThreadTest.cpp -lc++
    

    On MacOSX, builds and runs, and if we do:

    otool -L a.out 
    a.out:
        /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.0.0)
    

    We can see that we've needed to link nothing extra to make this work - nor has it happened behind the scenes. It seems to be very much a platform implementation detail that pthreads is a separate library.

    Having a choice of threading libraries with the pthread interface is legacy baggage on *NIX systems, many of which started off without thread support, then went through a phase of user-space threads before having full kernel support. I guess it's still there because nobody likes making breaking changes.

    0 讨论(0)
提交回复
热议问题