C++:同时避免静态初始化顺序问题和竞争条件 [英] C++: Avoiding Static Initialization Order Problems and Race Conditions Simultaneously

查看:30
本文介绍了C++:同时避免静态初始化顺序问题和竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Windows XP/Visual C++ 2008.

I'm using Windows XP / Visual C++ 2008.

我遇到了一个 C++ 静态初始化顺序问题,我用著名的首次使用时构造"的习惯用法解决了这个问题:

I've run into a C++ static initialization order problem, which I've solved with the well-known "construct on first use" idiom:

Foo foo; // Forget this

Foo &foo() // Do this instead
{
   // Use ptr, not reference, to avoid destruction order problems
   static Foo *ptr = new Foo();
   return *ptr;
}

但是,我一直在四处寻找,似乎 Windows(我的平台)并不能保证本地静态的线程安全,尽管它确实为全局静态提供了这种保证.

However, I've been searching around and it appears that Windows (my platform) does not guarantee thread-safety of local statics, though it does make this guarantee for global statics.

因此,如果我将对象设为全局对象,则可以获得线程安全性,但会遇到初始化顺序问题.如果我使用首次使用时构造",我可以避免初始化顺序问题,但我会遇到竞争条件.如何同时解决这两个问题?

So, if I make my object global, I get thread safety but I have initialization order problems. If I use "construct on first use", I avoid initialization order problems but I get race conditions. How can I solve both problems simultaneously?

推荐答案

在 C++ 2011 中,您使用 std::call_once():

In C++ 2011 you use std::call_once():

#include <mutex>
void initialize(Foo*& ptr)
{
    ptr = new Foo();
}
std::once_flag flag
Foo& foo()
{
    static Foo* ptr(0);
    std::call_once(flag, initialize, std::ref(ptr));
    return *ptr;
}

如果您不能使用 C++2011,您可能需要查看系统的底层设施.对于 POSIX,这将是 pthread_once().我不知道在其他平台上是如何完成的.

If you can't use C++2011 you might want to look at system's underlying facilities instead. For POSIX this would be pthread_once(). How this is done on other platform I don't know.

也就是说,我建议不要使用它,因为它本质上是某种形式的全局数据,通常没有充分的理由使用它.有例外,但它们很少见.实际上非常罕见.

That said, I recommend not to use this because it is essentially some form of global data and there is generally no good reason to use this. There are exceptions but they are rare. Extremely rare, actually.

这篇关于C++:同时避免静态初始化顺序问题和竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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