MultiThreading
 All Modules Pages
Safe initialization of data

Sometimes it is sufficient to care about safe initialization of data (e.g. creating a singleton instance of some data). After initialization data will not change and several threads may read the data whithout any need for synchronization mechanisms.

std::call_once

You can use a special flag, which ensures that some code called under the condition of this flag is called only once:

// global flag, alternatively defined as a class attribute
std::once_flag g_myOnceFlag;

Somewhere there is some code, which may be called several times, but executing the initialization only once:

std::call_once(g_myOnceFlag,SomeInitFunction);

Static variables within a code block

The C++11 runtime library ensures that static variables are created thread safe:

class MySingleton
{
public:
static MySingleton& GetInstance()
{
static MySingleton theSingleton; // ##
return theSingleton
}
};

This is the Meyers Singleton Pattern which works both in single threaded and multi threaded environments;

Hint: Never use double checked locking
Within "double checked locking" there is a simple check (e.g. if a singleton poinnter is already set) and only if this is not the case some mutex is acquired to safely create the singleton instance only within one thread. But even the simple check for the pointer is not safe. The pointer may be differnet from 0 but the data he points to may not yet be initialized!