Using Thread Safe Variables to Protect Data
- Updated2023-02-21
- 1 minute(s) read
Using Thread Safe Variables to Protect Data
Thread safe variables combine your variable and an OS thread-locking object into a single entity. This approach offers the following advantages over using a thread lock to protect a piece of data:
- Using thread safe variables can help you avoid one of the most common errors in multithreaded programs: forgetting to get a lock before accessing a variable.
With thread safe variables, you must call a Utility Library function to get access to the data. Because the API function acquires the OS thread-locking object, you will not accidentally access the data without acquiring the OS thread-locking object. - This approach also makes it easier to pass protected data between functions because you have to pass only the thread safe variable handle rather than passing a thread-lock handle and the variable that it protects.
The LabWindows/CVI Utility Library contains functions for creating and accessing thread safe variables. With these functions, you can create thread safe variables of any type. Typically, you do not call the LabWindows/CVI Utility Library thread safe variable functions directly. Instead, you can use macros that provide type-safe wrapper functions around the Utility Library functions. In addition to providing type safety, these macros also help you avoid forgetting to release the lock after accessing the data and attempting to release the lock without previously acquiring the lock.