-1

I'm implementing a thread safe singleton class in C++. I need a way of initializing the mutex which guards the getInstance() method.

This is a self contained shared library, so I can't use a mutex from another class, I have to find a way to initialize it inside the class.

The library has to be ported to various platforms, so let's consider that the mutex is:

static void * OS_mutex;

and to initialize it you use

OS_Mutex_Init ( void * mutex);

I tried to implement a nested class which in it's constructor I initialize the OS_mutex structure.

but I ran into some troubles, Does anyone knows a way to achieve what I need ? Any references, or links will be much appreciated.

stdcall
  • 27,613
  • 18
  • 81
  • 125
  • 2
    Quite curious what kind of troubles did you get? – sleepsort Dec 11 '12 at 15:58
  • So, what's the problem exactly? Are you trying to target some ancient platform that doesn't just do thread-safe initialisation of static members for you? – Nicholas Wilson Dec 11 '12 at 15:58
  • @NicholasWilson This solution has to work within Linux, Android (bionic lib), Windows 8, etc. I can't make any assumption regarding the implementation of mutex's. – stdcall Dec 11 '12 at 16:02
  • If you -1, provide a comment ! – stdcall Dec 11 '12 at 16:03
  • @Mellowcandle I got that; the question is, what makes you think your static initialisers aren't already thread-safe? Surely they are even on bionic, because it's so cheap for the compiler just to bang in a test-and-set for you (ARM and x86 are the fast platforms). – Nicholas Wilson Dec 11 '12 at 16:04

1 Answers1

0

First, declare it as a variable:

static MyStruct OS_Mutex;

Where:

struct MyStruct
{
    void* pointer;
    MyStruct() : pointer(0)
    {
        // Called on initialization of global variables by the CRT

        // You can call here your function OS_Mutex_Init()
        // Or you can use lazy initialization (leave the pointer to 0,
        // and initialize it only when someone needs it)
    }
};

Then, these two answers might help you:

Community
  • 1
  • 1
Synxis
  • 9,236
  • 2
  • 42
  • 64