Sample24: Semaphores

This article describes the use of semaphores.

Download

Here you can access the source code for this sample.

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 Sample24: Semaphores 1:.
The sample is ready for operation.

Description

The sample contains a "LargeObjPool", which contains two "LargeObj" for processing by the "LargeObjProcessors".

Sample24: Semaphores 2:

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":

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.