One-Time Initialization

Components are often designed to perform initialization tasks when they are first called, rather than when they are loaded. The one-time initialization functions ensure that this initialization occurs only once even when multiple threads may attempt the initialization.

Many applications use the interlocked functions to ensure that only one thread performs the initialization. It is better to use the one-time initialization functions for the following reasons:

  • They are optimized for speed.
  • They create the appropriate barriers on processor architectures that require them.
  • They support both locked and parallel initialization.
  • They avoid internal locking so the code can operate asynchronously or synchronously.

The initialization process is managed through a one-time initialization structure. This structure contains data and state information.

Synchronous Mode

The following steps describe one-time initialization in synchronous mode.

  1. Initially, the data stored with the initialization structure is NULL.
  2. When the first thread successfully calls the InitOnceBeginInitialize function (without the INIT_ONCE_ASYNC flag), one-time initialization begins. Subsequent threads that attempt this initialization are blocked until this initialization completes or fails; if the first thread fails the next thread is allowed to attempt the initialization and so on. The calling thread should create a synchronization object and specify it in the lpContext parameter of the InitOnceComplete function.

    Alternatively, the first thread can call the InitOnceExecuteOnce function to begin one-time initialization and execute the InitOnceCallback callback function. The callback function should return a handle to the synchronization object in its lpContext parameter.

  3. If the initialization succeeds, the lpContext handle is stored in the initialization structure. Subsequent initialization attempts return this context data. If the initialization fails, the data is NULL.

Asynchronous Mode

The following steps describe one-time initialization in asynchronous mode.

  1. Initially, the data stored with the initialization structure is NULL.
  2. When the first thread successfully calls the InitOnceBeginInitialize function with the INIT_ONCE_ASYNC flag, one-time initialization begins. Concurrent attempts to initiate initialization do not change the state, but proceed as expected. Each thread should create a synchronization object and return it in the lpContext parameter of the InitOnceComplete function. One thread will succeed in the completion attempt and the others must clean up their initialization.
  3. If initialization succeeds, the lpContext handle is stored in the initialization structure. Subsequent initialization attempts return this context data.

See Also

Using One-Time Initialization

Send comments about this topic to Microsoft

Build date: 11/19/2009

Tags :


Page view tracker