Question:
How can the data inconsistency of global 32-bit variables be avoided by using semaphores?
Response:
When in a task of lower priority, a value is assigned to a global 32-bit variable, a task of higher priority can interrupt the one of lower priority. If the task of higher priority accesses this global variable, the result is not correct (data inconsistency) due to the interrupted assignment instruction in the task of lower priority.
The write or read access can only be interrupted by a task of higher priority when variables with data types > 16-bit are used (e. g. DWORD, REAL, structures,...). This may lead to data inconsistency.
The problem of data inconsistency can be remedied by avoiding the read or write access as long as this global variable is written in another task. The following PLC logic (in structured text) shows this function as an example:
Variable g_bSema is declared as global, Boolean variable.
Variable g_dnVar is declared as global 32-bit variable.
Task1 (Task of lower priority)
g_bSema:=TRUE; (*activated semaphore *)
g_dnVar:=11111; (*read access to the global 32-bit variable*)
g_bSema:=FALSE; (*deactivated semaphore *)
Task2 (Task of higher priority)
(*read access to global variable is only allowed if the *)
(*semaphore is not active, otherwise the old value remains*)
(*unchanged *)
IF (g_bSema = FALSE) THEN
dnVarLocal:=g_dnVar;
END_IF