Listing 1: A test program to detect thread synchronization problems in creating a singleton object

#include <windows.h>
#include <process.h>
#include <stdio.h>

//#include "try1.h"
//#include "try2.h"
//#include "try3.h"
#include "solution.h"

Singleton::Singleton()
{
   printf("Singleton 0x%08X has been allocated by tid %d\n",
      this, ::GetCurrentThreadId());
 
   Sleep(1000); // Simulate a long operation.

   state = 0xABCD; // Initialize dummy state.
   printf("Singleton 0x%08X -state initialized by tid %d\n",
      this, ::GetCurrentThreadId());
}

void Singleton::show_state()
{
   printf("show_state(): this=0x%08X state=0x%04X tid=%d\n",
      this, state, ::GetCurrentThreadId());
}

void join(long thread_handle)
{
   // Join with thread.
   WaitForSingleObject(reinterpret_cast<HANDLE>(thread_handle),
      INFINITE);
}

void thread2(void*)
{
   printf("thread2 tid is %d\n", ::GetCurrentThreadId());
   Singleton::instance().show_state();
}

int main(void)
{
   printf("main tid is %d\n", ::GetCurrentThreadId());
   long spawned_thread = _beginthread(thread2, 0, NULL);

   Singleton::instance().show_state();
   join(spawned_thread);
   Singleton::instance().show_state();

   return 0;
}