1

I am analyzing a crash dump and found that I have a race condition in the local static object initialization. I am using MSVC++12.0 which doesn't have a thread safe static initialization.

Here is the minimal version of the program.

#include <iostream>
#include <thread>
#include <chrono>
#include <Windows.h>

class internalClass
{
public:
    internalClass(int parm) : value(parm) {}
    int value;
};

class externalClass
{
public:
    externalClass(int parm)
    {
        Sleep(1000*10);
        dp = new internalClass(parm);

    }
    void print()
    {
        std::cout << dp->value << "\n";
    }
    ~externalClass()
    {
        delete dp;
    }
    internalClass *dp;
};

static void foo()
{
    static externalClass obj(50);
    obj.print();
}

int main()
{
    std::thread t1(foo);
    Sleep(1000);
    std::thread t2(foo);
    t1.join();
    t2.join();
}

In the main program, externalClass is actually used for resource synchronization.

samnaction
  • 1,194
  • 1
  • 17
  • 45
  • You can avoid the thread safety issue by ensuring that the first call to `foo` is before you start threads. Call `foo` from `main` before you create the first thread. In this case you'd probably want to add something to not call `obj.print()` when you do that. – 1201ProgramAlarm Jan 17 '20 at 04:50
  • Is static member variable thread safe? So that I can put static variable as part of a class – samnaction Jan 17 '20 at 06:14
  • If I put externalClass as static object in a class, then it will be initialized before the threads starts. Does this approach have any issue ? – samnaction Jan 17 '20 at 15:05
  • @nonock can you share some examples for object construction using atomic. All I seeing is using atomic on integral types – samnaction Jan 17 '20 at 15:12
  • A static member variable (or global variable) will be initialized before `main` starts execution. Threading is usually not a concern at this point unless some initializer creates them. There can be issues with order of initialization for variables declared in different translation units. – 1201ProgramAlarm Jan 17 '20 at 15:57
  • just googled: https://www.drdobbs.com/testing/debugging-multithreaded-applications-in/240158201 As part of the debugger, Visual Studio provides a "Threads" window that lists all of the current threads in the system. From this window, you can: Freeze (suspend) or thaw (resume) a thread. This is useful when you want to observe the behavior of your application without a certain thread running. Switch the current active thread... –  Jan 17 '20 at 23:34

0 Answers0