Design Singleton class for multi-threaded environment in C++

Answer: For c++ thread safe singleton class design for multi threaded environment, we need to synchronize the function that creates and returns singleton object.

We will see the singleton class design without synchronization and with synchronization applying on function that create singleton object in C++

For example, in the below design “GetInstance()”  function is not thread safe.

As multiple threads can enter into the “if(NULL == s_instance)” block and can create multiple singleton instances.

 

So, to have unique instance across the application in multi-threaded environment, we need to put some lock above and below of conditional block, so only one thread can enter into it and create object. Once, one thread has created an object other thread will not be allowed.

First, let’s test if below c++ singleton class design needs synchronization.

We know that for singleton class only one object will be created. So, lets, test the above design with below test code and see if we can get the same address of objects on different call of GetInstance() function in multi-threaded application.

Here is the output for the below test sample. Notice that both addresses are different, means, both main thread and child thread have created different objects that violets singleton class design.

Output:

constructor…
Address of object in main thread:006981B0
constructor…
Address of object in thread:006981E0
Thread handle closed.

Note: you may not always get different addresses but same and you need to run test code multiple times.

Test sample:

 

 

C++ thread safe Singleton class design

Note that we have put two if(NULL == s_instance)condition. One condition prevent execution of _lock.acquire()and _lock.release()on multiple GetInstance() method call. And second condition, will prevent multiple thread to enter into the block and to creat multiple objects.

Now, if you run the above test sample, we will always get unique address of objects on multiple calls.

Note:In an interview, this c++ thread safe singleton class interview question can also be asked as “in singleton class, what code you will synchronize for thread safety?”