Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

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

Why does specifying -std=c++11 when compiling a program that directly or indirectly uses std::thread not imply -pthread? It seems strange that the implementation detail of std::thread using pthreads under the hood is exposed to the programmer; if it's a matter of giving the user a choice of posix-compatible threading libraries, why not just default to pthreads and have some --threading-model=<your_favorite_posix_threads_library> argument to override it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
";
        }};
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...