What Is a Semaphore?

Updated Mar 5, 2019

Reported In

Software

  • LabVIEW

Issue Details

What is a semaphore and how is it useful in LabVIEW?

Solution

A semaphore is a way to limit the number of tasks that can simultaneously operate on a shared, protected resource. A protected resource or critical section of code might include writing to global variables or communicating with external instruments. You can use semaphores to make your code thread-safe, and to prevent race conditions. A semaphore is similar to a mutex (Mutual exclusion object) in other programming languages. 

It is useful for protecting two or more critical sections of code that should not be called concurrently. Before entering a critical section, the thread must acquire a semaphore. If no thread is already in the critical section, the thread proceeds to enter that part of the diagram immediately. This thread must release the semaphore once the critical section is complete. Other threads that want to enter the critical section must wait until the first thread releases the semaphore.
 

Figure 1: The VIs on the Semaphore Palette (Programming » Synchronization » Semaphore)
 
 
To accomplish this, obtain a semaphore reference and then place the Acquire Semaphore and Release Semaphore VIs at the beginning and end, respectively, of each critical section. Then each critical section can acquire and release the semaphore one at a time to assure proper data control. At the end of the code use the Release Semaphore Reference VI.

Additional Information

Look for example programs in the LabVIEW shipping examples. Open LabVIEW » Help » Find Examples and search for semaphore in the search tab.

WAS THIS ARTICLE HELPFUL?

Not Helpful