Semaphores
Semaphores are used to synchronize access to limited resources. They can also be used to implement a notification event. Semaphores are provided by the TwinCAT real-time through the CSemaphoreInstance class.
CSemaphoreInstance
The CSemaphoreInstance class provides the interface for handling semaphores. To create a semaphore, the instance requires the object ID of the TwinCAT real-time instance, which is available via OID_TCRTIME_CTRL, as well as a reference to the TwinCAT object server via a pointer to ITComObjectServer.
Methods:
- HRESULT SemCreate(WORD nCntInit, OTCID oid, ITComObjectServer* ipSrv); Creates the semaphores with nCntInit as initial value of the available resources. Returns S_OK if successful and E_FAIL if the semaphore cannot be generated.
- HRESULT SemDelete(); SemDelete() deletes the semaphore. Returns S_OK.
- HRESULT SemPost() SemPost() increases the number of available resources. If a task is waiting for the semaphores, the task with the highest priority is released, i.e. it can continue its execution. Returns S_OK if successful. Possible error codes:
MAKE_RTOS_HRESULT(51) | Semaphore overflow. For example, if the internal memory is insufficient. |
- HRESULT SemPend(OSTICKS nTimeout); Reduces the number of available resources; if no resources are available, the task is blocked at this point.
SemPend() waits for a semaphore until it is available. A timeout can be specified in OSTICKS and is therefore processor dependent. The ITcRTime interface in can be used to calculate it. In the sample TcSemaphoreSample a method TimeoutMsToTicks was used for this purpose. Special values for nTimeout:
RTIME_NOWAIT (-1) | Method immediately returns S_OK if the semaphore is available. |
RTIME_ENDLESSWAIT (0) | Method waits indefinitely for availability of the semaphores |
The method returns S_OK if the semaphore was successfully obtained; otherwise:
MAKE_RTOS_HRESULT(10) | Indicates a timeout. If nTimeout is set as RTIME_NOWAIT, this semaphore is not available. |
Sample: