One-time initialization and thread safety

At times, you might want to defer the initialization of resources until a thread requires them. However, your application might require that multiple threads use a certain resource, which requires you to initialize the resource only once in a threadsafe way.

There are several ways you can initialize a resource that is used multiple times in a threadsafe fashion. Most of these methods involve a Boolean value to allow the application to quickly determine whether the required initialization is completed. You must also use a synchronization technique in addition to the Boolean flag to ensure that the initialization completed.

Related concepts
Function calls that are not thread safe
Common multithreaded programming errors
Related reference
Example: Space location locks in Pthread programs
Thread-specific data