Local, Global, or Network Shared Variable Can Cause Race Conditions

Updated Oct 23, 2023

Reported In

Software

  • LabVIEW

Issue Details

  • I have two independent while loops running in parallel. The first while loop is acquiring data and storing it in a local, global, or shared variable. The second loop is periodically reading the data from a local, global, or shared variable. Most of the time everything runs smoothly, but sometimes I lose data and the variable becomes empty.
  • I have a Network Shared Variable that is used on the host computer while other computers are reading the variable and occasionally see unexpected results.

Solution

Queues implemented in a Producer/Consumer architecture are most commonly used to avoid data starvation or data overflow. Using a Producer/Consumer architecture provides a synchronization advantage because the Consumer loop only executes when there is data available in the queue. Refer to Producer/Consumer Architecture in LabVIEW for more information.

An alternative is to use Semaphores or Functional Global Variables, which effectively lock the variable resource while you write to it.

Additional Information

What Causes This?

Using two or more parallel loops to write to and read from the same variable or trying to access a Network Shared Variable while a value is being written to it, can cause a race condition in the following scenarios:

  • A loop is reading the value of a local, global, or shared variable, and another is writing to the value of the local, global, or shared variable. If they are not synchronized, then the value could be read before it has actually been sent or vice-versa.
  • A computer is writing data to the Network Shared Variable and other computers try to access the value at the same time.