10

重複の可能性:
gccのC ++ 11 thread_local-代替案
GCCの__threadを使用してthread_localを完全にエミュレートする方法はありますか?

c ++ 11thread_localを使用してthread_local変数を作成して使用したかったのですが、gccでまだサポートされていないため、gcc固有のを使用しています__thread。私が変数を宣言した方法は

myClass
{
public:

  static __thread int64_t m_minInt;

};
__thread int64_t myClass::m_minInt = 100;

コンパイルすると、次のようなエラーが発生します

error: ‘myClass::minInt’ is thread-local and so cannot be dynamically initialized

適切にそれを行う方法は?

PS:gccバージョン:4.6.3

4

1 に答える 1

6

遅延初期化を使用する必要があります。

myClass
{
public:

  static __thread int64_t m_minInt;
  static __thread bool m_minIntInitialized;

  static int64_t getMinInt();
};
__thread int64_t myClass::m_minInt;
__thread bool myClass::m_minIntInitialized;


int64_t myClass::getMinInt()
{
  if (!m_minIntInitialized)  // note - this is (due to __thread) threadsafe
  {
    m_minIntInitialized = true;
    m_minInt = 100;
  }

  return m_minInt;
}

m_minIntInitializedゼロであることが保証されています。

ほとんどの場合(ELF仕様)、ゼロで初期化される.tbssセクションに配置されます。

C++の場合-http://en.cppreference.com/w/cpp/language/initialization

他のすべての非ローカル静的変数およびスレッドローカル変数の場合、ゼロ初期化が行われます。実際には、ゼロで初期化される変数は、プログラムイメージの.bssセグメントに配置されます。このセグメントは、ディスク上のスペースを占有せず、プログラムのロード時にOSによってゼロにされます。

于 2012-08-22T14:35:12.507 に答える