为什么在GCC和Clang中使用std :: thread需要-pthread? [英] Why is -pthread necessary for usage of std::thread in GCC and Clang?

查看:490
本文介绍了为什么在GCC和Clang中使用std :: thread需要-pthread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在编译直接或间接使用std::thread的程序时指定-std=c++11并不表示-pthread?奇怪的是,

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)

在后台使用pthreads的实现细节向程序员公开了.如果要让用户选择与posix兼容的线程库,那为什么不只是默认使用pthreads并使用一些--threading-model=<your_favorite_posix_threads_library>参数来覆盖它呢?

解决方案

使用std::thread并非普遍要求使用-pthread选项-这是您所构建的任何平台的一种实现方式.

编译:

 #include <thread>
#include <iostream>

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

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

在MacOSX上,可以构建并运行,如果可以,则:

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)

我们可以看到,无需进行任何额外的链接即可完成此工作-也不在幕后发生. pthreads是一个单独的库,似乎在很大程度上是一个平台实现的细节.

在* NIX系统上,具有pthread接口的线程库可供选择,这是传统的包systems,其中许多是在没有线程支持的情况下开始的,然后经历了用户空间线程的阶段,才获得了完整的内核支持.我猜它仍然存在,因为没人喜欢进行重大更改.

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?

解决方案

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.

这篇关于为什么在GCC和Clang中使用std :: thread需要-pthread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆