Link to home
Start Free TrialLog in
Avatar of julieha
julieha

asked on

How do I design a singleton class ?

Can you help me designing a singleton class that works in a multithreaded environment?
Avatar of ikework
ikework
Flag of Germany image

here is an example how a singleton class looks like:

http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp

in multithreaded environments you just have to make sure, that its operations are protected by a mutex in order to make them atomar, here is an example of a mutex:

http://www.gamasutra.com/features/20051205/paquet_01.shtml

in that example the global variable "g_iResult" is protected by a mutex


ike
Avatar of julieha
julieha

ASKER

Hello Expert,
For example, the varialbe "g_iResult" is protected by a mutex, but then how do i implement it to a singleton class? Can you help me how to do it with the below codes or show me any example codes which singleton class actually works in the mutex environment? I am a beginner in the field, and I need to have this done soon. Thank you so much for your help!

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

HANDLE g_hMutex;
bool g_bThreadOneFinished = false;
bool g_bThreadTwoFinished = false;
int g_iResult = 0;

void ThreadOne( void *)
{
  for ( int i = 0; i < 10000; i++)
  {
      WaitForSingleObject(g_hMutex, INFINITE);
    g_iResult += 1;
    ReleaseMutex(g_hMutex);
  }

  g_bThreadOneFinished = true;
  _endthread();
}

void ThreadTwo( void *)
{
  for ( int i = 0; i < 10000; i++)
  {
    WaitForSingleObject(g_hMutex, INFINITE);
    g_iResult += 1;
    ReleaseMutex(g_hMutex);
  }

  g_bThreadTwoFinished = true;
  _endthread();
}

int main()
{
  g_hMutex = CreateMutex(NULL, FALSE, "MutexName");

  _beginthread(ThreadOne, 0, NULL);
  _beginthread(ThreadTwo, 0, NULL);

  while (( false == g_bThreadOneFinished)
  || ( false == g_bThreadTwoFinished))
  {
    Sleep(1);
  }

  CloseHandle(g_hMutex);

  printf("Result: %i\n", g_iResult);
}
ASKER CERTIFIED SOLUTION
Avatar of ikework
ikework
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Take a look at http://www.codeproject.com/KB/architecture/singleton.aspx ("Singleton Pattern: A review and analysis of existing C++ implementations"), and the subsection "Resolving the multi-threading issue" in particular. The article comes with full source code.