Using Macros to Interact with Thread Safe Variables
- Updated2023-02-21
- 2 minute(s) read
Using Macros to Interact with Thread Safe Variables
Use the DefineThreadSafeScalarVar and DefineThreadSafeArrayVar macros to create thread safe variablesthread safe variables and the type-safe wrapper functions, or accessor functions, that you use to access them. If you need to access the thread safe variable from more than one source file, use the DeclareThreadSafeScalarVar or DeclareThreadSafeArrayVar macro in an include (.h) file to create declarations for the accessor functions.
Calling Accessor Functions
These macros create the following accessor functions:
- InitializeVariableName—You must initialize the thread safe variable once—that is, from only one thread—in your program. You typically do this from your program's main thread at startup. You must initialize the thread safe variable before you can access it from any thread. Make the following function call to initialize the thread safe variable:
InitializeVariableName (); - GetVariableName—This function is created only by the DeclareThreadSafeScalarVar macro. You can get the value of the variable from any thread by calling:
int value = GetVariableName (); - SetVariableName—This function is created only by the DeclareThreadSafeScalarVar macro. You can set the value of the variable from any thread by calling (where newValue is an integer):
SetVariableName (newValue); - GetPointerToVariableName—Another thread can change the value between your calls to the Get and Set accessor functions. If you must modify the value of a thread safe variable in a way that relies on the previous value of the variable (for example, incrementing an integer), you must use the pointer to the thread safe variable. No other threads can read or modify the value of the variable while you have the pointer. To get the pointer to the value from any thread, call the following code:
int *valuePtr = GetPointerToVariableName (); - ReleasePointerToVariableName—You must subsequently call, from the same thread, the following function to release the pointer before the variable can be accessed from any other thread:
ReleasePointerToVariableName ();
Note You can call GetPointerToVariableName more than once from the same thread (it does not block on subsequent calls), but you must call ReleasePointerToVariableName exactly once for each call you make to GetPointerToVarialeName. If you call ReleasePointerToVariableName without a previous matching call to GetPointerToVariableName in the same thread, ReleasePointerToVariableName reports a run-time error. - UninitializeVariableName—Finally, you uninitialize the variable before your program terminates by calling:
UninitializeVariableName ();