线程安全的静态变量没有mutexing? [英] Thread-safe static variables without mutexing?

查看:159
本文介绍了线程安全的静态变量没有mutexing?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得读这里面的方法声明为static变量不是线程安全的。 (请参见怎么样Meyer的单?由<一提到href=\"http://stackoverflow.com/questions/1052168/thread-safe-static-variables-without-mutexing/1052197#1052197\">Todd加德纳)

I remember reading that static variables declared inside methods is not thread-safe. (See What about the Meyer's singleton? as mentioned by Todd Gardner)

Dog* MyClass::BadMethod()
{
  static Dog dog("Lassie");
  return &dog;
}

我的库生成C ++ code为最终用户来编译他们的应用程序的一部分。在code将其产生的需求在一个线程安全的跨平台的方式来初始化静态变量。我想使用的boost :: call_once的来互斥变量初始化但最终用户暴露在加速的依赖。

My library generates C++ code for end-users to compile as part of their application. The code it generates needs to initialize static variables in a thread-safe cross-platform manner. I'd like to use boost::call_once to mutex the variable initialization but then end-users are exposed to the Boost dependency.

有没有我这样做不强制对终端用户额外的依赖的方式?

Is there a way for me to do this without forcing extra dependencies on end-users?

推荐答案

您是正确的,这样的静态初始化不是线程安全(的这里是一篇文章讨论什么,编译器会把它变成)

You are correct that static initialization like that isn't thread safe (here is an article discussing what the compiler will turn it into)

目前,没有标准的,线程安全的,可以移植到初始化静态单身的方式。双重检查锁定模式可以使用,但你需要潜在的不可移植的线程库(见讨论<一个href=\"http://www.devarticles.com/c/a/Cplusplus/C-plus-in-Theory-Why-the-Double-Check-Lock-Pattern-Isnt-100-ThreadSafe/3/\"相对=nofollow>这里)。

At the moment, there's no standard, thread safe, portable way to initialize static singletons. Double checked locking can be used, but you need potentially non-portable threading libraries (see a discussion here).

下面是几个选项,如果线程安全性是必须的:

Here's a few options if thread safety is a must:


  1. 请不要偷懒(加载):静态初始化期间初始化。这可能是一个问题,如果另一个静态调用这个函数在它的构造函数,因为静态初始化的顺序是不确定的(见的这里)。

  2. 使用升压(如你所说),或洛基

  3. 滚你
    您的支持平台上的单
    (或许应该避免,除非
    你是一个线程专家)

  4. 锁,你需要访问一个互斥每次。这可能是很慢的。

例1:

// in a cpp:
namespace {
    Dog dog("Lassie");
}

Dog* MyClass::BadMethod()
{
  return &dog;
}

示例4:

Dog* MyClass::BadMethod()
{
  static scoped_ptr<Dog> pdog;
  {
     Lock l(Mutex);
     if(!pdog.get())
       pdog.reset(new Dog("Lassie"));
  }
  return pdog.get();
}

这篇关于线程安全的静态变量没有mutexing?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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