簡體   English   中英

在VS2015中C ++本地靜態變量初始化是否是線程安全的

[英]Is C++ local static variable initialization thread-safe in VS2015

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

VS2015支持Magic statics( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm

但是,在調試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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM