MultiThreading
|
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.
You can use a special flag, which ensures that some code called under the condition of this flag is called only once:
Somewhere there is some code, which may be called several times, but executing the initialization only once:
The C++11 runtime library ensures that static variables are created thread safe:
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!