4

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

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 - ???
}
4

1 回答 1

3

你需要:

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