TAS real-valued function As an example of the use of shared variables, consider this eV+ program that increments and decrements a global variable: .PROGRAM tas_test() AUTO i FOR i = 1 TO 1E+06 counter = counter+1 counter = counter-1 END .END If the variable counter starts at 0, and the program tas_test is run simultaneously in tasks 1 and 2, one might expect that counter will have the value 0 after execution completes. In fact, it usually will not have that value! Since the two tasks are modifying the same variable at the same time, the value gets corrupted. That can be fixed by modifying the program to employ an interlock as follows:
.PROGRAM tas_test() AUTO i FOR i = 1 TO 1E+06 ; Wait for access to the shared variable to be ; unlocked, and set the lock for our access. WHILE TAS(locked,TRUE) DO WAIT END ; Access the shared variable. counter = counter+1 counter = counter-1 ; Release access to the shared variable. locked = FALSE END .END Now, when the program is executed simultaneously in two (or more) tasks. The value of the variable counter will always end up the same as before the program starts. That's because each task blocks the other task(s) while accessing the shared variable.
(The global variable locked does not need to be initialized before the program is executed, because the TAS function returns FALSE if the variable is not defined. Thus, the lock implicitly starts out being off.) NOTES: The lock should be released as soon as possible, because the other task could be waiting for it to be released. Take care to make sure the lock is always released after it gets applied. Otherwise the other task could be blocked forever, and the current task would also be blocked the next time it tries to acquire the lock. eV+Language Reference Guide, v2.x, 18319-000 Rev A Page 522