任何C ++ 11线程安全性保证适用于使用C ++ 11编译/链接的第三方线程库吗? [英] Do any C++11 thread-safety guarantees apply to third-party thread libraries compiled/linked with C++11?

查看:143
本文介绍了任何C ++ 11线程安全性保证适用于使用C ++ 11编译/链接的第三方线程库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11提供的功能包括线程安全初始化的静态变量,并引用这个问题,我们会说:

C++11 offers features like thread-safe initialization of static variables, and citing that question we'll say for instance:

Logger& g_logger() {
    static Logger lg;
    return lg;
}

这样表面上C ++ 11编译器包括线程头,或者生成其主体中的任何线程。

So ostensibly (?) this is true regardless of whether a module compiled with a C++11 compiler included the thread headers, or spawned any threads in its body. You're offered the guarantee even if it were linked against another module that used C++11 threads and called the function.

但是,如果你的其他模块是这样的,如果你使用C ++ 11线程,调用这个代码不是使用C ++ 11线程,而是像Qt的 QThread 。是原子初始化的静态,然后在C ++ 11的范围之外的能力做出这样的保证?或者一个模块的编译与C ++ 11然后链接到其他C ++ 11代码的意思暗示,你会得到保证无论如何?

But what if your "other module" that calls into this code wasn't using C++11 threads, but something like Qt's QThread. Is atomic initialization of statics then outside of the scope of C++11's ability to make such a guarantee? Or does the mere fact of a module having been compiled with C++11 and then linked against other C++11 code imply that you will get the guarantee regardless?

推荐答案

您的示例依赖于内存模型,而不是基于线程实现。执行此代码的任何人都将执行相同的指令。如果两个或多个核心执行这个代码,他们将遵守内存模型。

Your example relies on the memory model, not on how threads are implemented. Whoever executes this code will execute the same instructions. If two or more cores execute this code, they will obey the memory model.

基本实现等效于:

std::mutex mtx;
Logger * lg = 0;
Logger& g_logger() {
    std::unique_lock<std::mutex> lck(mtx);
    if (lg == 0)
        lg = new Logger;
    return *lg;
}

可以优化此代码以使用双重检查锁定模式其在特定处理器架构(例如,在x86上)可能快得多。另外,因为编译器生成这个代码,它会知道不要做疯狂的优化打破天真的DCLP。

This code may be optimized to use the double-checked locking pattern (DCLP) which, on a particular processor architecture (e.g., on the x86) might be much faster. Also, because the compiler generates this code, it will know not to make crazy optimizations that break the naive DCLP.

这篇关于任何C ++ 11线程安全性保证适用于使用C ++ 11编译/链接的第三方线程库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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