Combining Multiple Variables into a Single Thread Safe Variable
- Updated2023-02-21
- 1 minute(s) read
Combining Multiple Variables into a Single Thread Safe Variable
If you have two or more variables that are somehow related, you must prevent two threads from modifying the values at the same time. An example of this is an array and a count of the number of valid values in the array. If one thread removes values from the array, it must update both the array and the count before allowing another thread to access the data. Although you could use a single LabWindows/CVI Utility Library thread lock to protect access to both of these values, a safer approach is to define a structure and then use that structure as a thread safe variable. The following example shows how you can use a thread safe variable in this manner to safely add a value to the array.
typedef struct {
int data[500];
int count;
} BufType;
DefineThreadSafeVar(BufType, SafeBuf);
void StoreValue(int val)
{
BufType *safeBufPtr;
safeBufPtr = GetPointerToSafeBuf();
safeBufPtr->data[safeBufPtr->count] = val;
safeBufPtr->count++;
ReleasePointerToSafeBuf();
}