The multicore operator is an extension of the IEC 61131-3 standard.
The operator can be used for implementing a semaphore, for example to guarantee exclusive access to a variable written to by different tasks.
TEST_AND_SET
gets a type DWORD
variable as its input. Write access to this variable must be possible. The variable
is set to 1
and the previous value is returned as the result.
The operation is atomic, which means that it cannot be interrupted by another task. This also applies to multicore platforms.
For example, the call in the program is dwOldValue := TEST_AND_SET(dw);
, in which the variables dwOldValue
and dw
must be of data type DWORD
.
Example
The following example shows a typical usage. Exclusive access to a type STRING
variable, which is addressed via the pstrOutput
pointer, should be implemented. The access to a string is not atomic. If multiple
tasks write to the same string at the same time, then the contents may be inconsistent.
With the TEST_AND_SET
function, it is now possible to write the same STRING
variable in different tasks.
FUNCTION ExclusiveStringWrite : BOOL VAR_INPUT strToWrite : STRING; pstrOutput : POINTER TO STRING; END_VAR VAR_STAT dwSynch : DWORD; END_VAR VAR dwOldValue: DWORD; END_VAR dwOldValue := TEST_AND_SET(dwSynch); // Write the 1 and read the old value at the same time IF dwOldValue = 0 THEN // 0 means: no other task is currently writing pstrOutput^ := strToWrite; // Now you can write safely on the string dwSynch := 0; // The DWORD must be reset ExclusiveStringWrite := TRUE; // Writing was successful ELSE ExclusiveStringWrite := FALSE; // Writing was not successful