在VS2015中c++局部静态变量初始化线程安全吗?
Is C++ local static variable initialization thread-safe in VS2015
根据https://msdn.microsoft.com/en-us/library/hh567368.aspx
Magic stats (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm)在VS2015上支持
但是在调试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 Start2 Sleeper Start3 Sleeper Start1卧铺Start4
这表明初始化静态变量s实际上不是线程安全的
是的。测试结果是错误的。从MyThreadFunction中删除单词sleeper将显示预期的输出
Start1 Sleeper Start4 Start3 Start0 Start2 Done3 Done1 Done0 Done2Done4
相关文章:
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 如何初始化大线程本地对象?
- 开始多线程代码之前的初始化
- 如何在堆上初始化线程?(使用 "new" 关键字)
- 线程局部变量的初始化顺序
- C++:用IIFE线程初始化静态局部变量安全吗
- 设置 JVM 通过 JNI 初始化时创建的线程数
- VC++6 线程安全静态初始化
- 启动线程会导致指针初始化时出现分段错误
- 线程局部变量的初始化
- 初始化线程的正确方法
- 通过例程初始化聚合
- 使用模板和可变模板进行线程初始化
- std::使用类参数的线程初始化会导致类对象被多次复制
- std::线程初始化构造函数给出编译错误
- 构造函数内的休眠线程和线程初始化
- SFML线程初始化不工作
- c++ 11线程初始化带有成员函数编译错误
- C++ 中的线程序列化是什么意思
- C++0x 线程初始化