c++ - C++局部静态变量初始化在VS2015中是线程安全的吗

标签 c++ visual-studio c++11 visual-studio-2015

根据 https://msdn.microsoft.com/en-us/library/hh567368.aspx

魔术静力学 ( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm ) VS2015 支持

但是在 debug x64 Vs2015 Update 3 中测试以下代码

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <tchar.h>

#define MAX_THREADS 5

class Sleeper
{
public:
    Sleeper()
    {
        std::cout << "Sleeper \n";
        Sleep(100000);
    }
};

DWORD WINAPI MyThreadFunction(LPVOID lpParam)
{
    std::cout << "Sleeper Start" << (int)lpParam << "\n";
    static Sleeper s;
    std::cout << "Sleeper Done" << (int)lpParam << "\n";
    return 0;
}

int main(int, char**)
{
    DWORD   dwThreadIdArray[MAX_THREADS];
    HANDLE  hThreadArray[MAX_THREADS];

    // Create MAX_THREADS worker threads.

    for (int i = 0; i<MAX_THREADS; i++)
    {
        // Create the thread to begin execution on its own.
        hThreadArray[i] = CreateThread(
            NULL,                   // default security attributes
            0,                      // use default stack size  
            MyThreadFunction,      // thread function name
            (LPVOID)i,               // argument to thread function 
            0,                     // use default creation flags 
            &dwThreadIdArray[i]);   // returns the thread identifier 

                                    // Check the return value for success.
                                    // If CreateThread fails, terminate execution. 
                                    // This will automatically clean up threads and memory. 
        if (hThreadArray[i] == NULL)
        {
            ExitProcess(3);
        }
    } // End of main thread creation loop.

      // Wait until all threads have terminated.
    WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);

    // Close all thread handles and free memory allocations.
    for (int i = 0; i<MAX_THREADS; i++)
    {
        CloseHandle(hThreadArray[i]);
    }

    return 0;
}

给出输出

Sleeper Start0 Sleeper Sleeper Start2 Sleeper Start3 Sleeper Start1 Sleeper Start4

这表明初始化静态变量s实际上不是线程安全的。

最佳答案

是的。测试是错误的。从 MyThreadFunction 中删除单词 sleeper 显示了预期的输出

Start1 Sleeper Start4 Start3 Start0 Start2 Done3 Done1 Done0 Done2 Done4

关于c++ - C++局部静态变量初始化在VS2015中是线程安全的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40390168/

相关文章:

c++ - 在 2 个 cpp 文件中定义一个 C++ 类?

visual-studio - 从命令行构建的 Xamarin.Forms android 应用程序不起作用

visual-studio - 如何清除测试方法的 [Ignore] 缓存? (无需重新启动 Visual Studio)

c++ - 委托(delegate)给默认的移动构造函数

c++ - 将 __m128i 值转换为 std::tuple

c++ - 将类成员指针传递给 Lambda 捕获列表 c++11

c++ - 在等号左侧使用右值引用的规则是什么?

c++ - 在 C 或 C++ 中取消引用数组时使用小数参数

c++ - 强制未使用的函数在共享库中导出

c# - LINQ 不适用于 Xamarin 中的字符串?