Sample24: Semaphores
This article describes the use of semaphores.
- 1. Unpack the downloaded ZIP file.
- 2. Open the zip file that it contains in TwinCAT 3 by clicking on Open Project ….
- 3. Select your target system.
- 4. Build the sample on your local machine (e.g. Build->Build Solution).
- 5. Note the actions listed on this page under Configuration.
- 6. Activate the configuration by clicking on .
- The sample is ready for operation.
Description
The sample contains a "LargeObjPool", which contains two "LargeObj" for processing by the "LargeObjProcessors".
The "LargeObjProcessors" are controlled by different tasks with different priorities that run on different CPU cores. In the info data area they count how often processing could be carried out ("Info->ProcessedObjCount") and how often no object was available for processing within the delay time ("Info->TakeObjFailedCount").
Understanding the sample
The LargeObjPool is initialized in the PS transition by the InitPool()
method with two LargeObj (defined by the parameter "ObjCount"). The pool essentially offers two methods, which are used by the "LargeObjProcessors":
TakeObj()
returns a LargeObj if one is available. Based on a semaphore, the system waits until a timeout occurs to see if an object is made available. The objects themselves are stored in a map. Access to the map is protected by a CriticalSection.ReturnObj()
provides a processed object to the pool for further processing.
In its CycleUpdate()
LargeObjProcessor uses TakeObj()
from the pool to obtain a LargeObj for processing. If this is successful, processing is simulated via the help function ConsumeTime()
before the LargeObj is returned to the pool via ReturnObj
.
Processing of all LargeObj must be complete before the system can be shut down. This is achieved by the LargeObjPool informing the TwinCAT system via TcTryLockOpState()
and TcReleaseOpState()
that an object is being processed. As long as the stored counter is not 0, the TcCOM object "Pool" is reset and only shut down later by the Op->SafeOp transition.