Race Condition demonstration demo script.
Open the Race Condition project and the Counter 1 and Counter 2 VIs.
Run both VIs.
While the VIs are running, open their block diagrams and describe what the two VIs are doing and provide an example of why you might want to do something similar.
Both VIs are incrementing a single counter, which is represented as a shared variable. An example of a real-world application is counting objects in a container as they arrive from two different paths.
Allow the VIs to run for a couple of minutes. Ideally, you should try them on your instructor computer ahead of the demo to determine how long they need to run. As a general rule of thumb, I've found that allowing the running count to get around 60k is usually sufficient, but the race condition tends to become apparent with fewer iterations on slow machines.
Stop both VIs and add up the Count 1 and Count 2 using the windows calculator. If you have run the VIs for long enough, Count 1 + Count 2 should be more than the Total Count. Ignore the running count for the math, the only purpose of the running count is to show you the count as the VI is running. Ask the students if they can identify the issue with the code, and then explain the race condition.
The race condition occurs because there is a critical section in the code. After each loop reads the value of the counter, it assumes that the counter is not going to change before it can write the incremented value. Sometimes, this assumption is correct, that is why the problem only shows up once or twice in thousands of iterations. Explain that the rarity of the problem is actually a bad thing rather than a good thing, since it makes the problem much harder to find and fix. The actual problem occurs when both loops read the value at approximately the same time, then they both increment the same value. When this happens, one of the increments is essentially lost.
Continue through the presentation. After you discuss semaphores and functional global variables, you can show the demo using semaphores or functional globals and demonstrate that Count 1 + Count 2 will always be equal to the Total Count if you protect the critical section.