繁体   English   中英

c ++中的静态初始化和线程安全性

[英]Static initialization in c++ and thread safety

类实例的静态初始化不是线程安全的。 下面的代码是不应该做的事情的一个例子:

extern int computesomething();

class cachedcomputation
{
public:
    cachedcomputation()
    {
        result = computesomething();
    }

    int result;
};

void usecached()
{
    static cachedcomputation c;

    // use of c.result - may break
}

但是,下面的代码是否是线程安全的? (忽略解决方案的丑陋)何时或为何会破坏?

extern int computesomething();

class cachedcomputation
{
public:
    cachedcomputation()
    {
    if(0==InterlockedCompareExchange(&mutex, 1, 0))
    {
        // first thread
            result = computesomething();
        InterlockedExchange(&mutex, 2);
    }
    else
    {
        // other thread - spinlock until mutex==2
        while(2!=InterlockedCompareExchange(&mutex, 2, 2)){}
    }
    }

    int result;

private:
    long mutex;
};

void usecached()
{
    static cachedcomputation c;

    // use of c.result - ???
}

你需要:

  • 初始化你的“互斥体”
  • 在if块的末尾重置“mutex”:InterlockedExchange(&mutex,0)
  • 可选地将if语句转换为while,因此您的代码将阻塞,直到“mutex”被解锁

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM