【问题标题】:static local CCriticalSection doesn't wok correctly静态本地 CCriticalSection 无法正常工作
【发布时间】:2019-02-01 15:56:05
【问题描述】:

我发现下面的代码 CCriticalSection 不能正常工作。

foo()
{
    //...
    {
        static CCriticalSection cs; //static local variable
        CSingleLock lock(&cs, TRUE);
        //Critical Section
        non_reentrant_function();
    }
    //...
}

但是这些代码很好:

static CCriticalSection cs; //define a global static variable

foo()
{
    //...
    {
        CSingleLock lock(&cs, TRUE);
        //Critical Section
        non_reentrant_function();
    }
    //...
}

众所周知,静态局部变量只有在第一次调用函数 foo 时才会被初始化。

如果多线程调用 foo,静态局部 CCriticalSection 会发生什么情况?

【问题讨论】:

标签: multithreading mfc


【解决方案1】:

如果您使用的是 2015 年之前的 Visual Studio,或者其他不支持 C++11“magic static”的编译器,则静态对象本身的构造不会正确同步。

即使在 Visual Studio 2015 / 2017 中,也可以选择禁用“magic static”(/Zc:threadSafeInit)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多