Admin Production ni-theme
Current Publication

Protecting Data in Multithreaded Applications

LabWindows/CVI

Protecting Data in Multithreaded Applications

A critical issue you must address in multithreaded programs is data protection. You must protect certain types of data—global variables, static local variables, and dynamically allocated variables—from simultaneous access by multiple threads. Failure to do so can cause intermittent logical errors that are difficult to find.

In general, you protect your data in a multithreaded program by associating an OS thread-locking object with the variable that holds your data. Any time you want to get or set the value of the variable, you first call an OS API function to acquire the OS thread-locking object. After getting or setting the variable, you release the thread-locking object. The OS allows only one thread to acquire a particular thread-locking object at a given time. If a thread calls the OS API function to acquire a thread-locking object while another thread owns it, the thread attempting to acquire the thread-locking object is not allowed to return from the OS API acquire function until the owning thread releases the thread-locking object. A thread that is trying to acquire a thread-locking object that is owned by another thread is referred to as a blocked thread.

If you need to communicate between different threads in your application, you can use global variables, thread safe variables, and thread safe queues to communicate between threads safely. You can use thread safe variables, thread safe queues, and thread locks to protect data. An important consideration when protecting data is avoiding deadlocks.

Note Note  You can use global variables to access and pass small amounts of data between threads, such as from a time-critical thread to a lower priority thread. Global variables can share data smaller than 32-bits, such as scalar data, between threads. However, global variables of larger data types require locking to prevent simultaneous access.