semWait (Function)

Top  Previous  Next

Architecture:

X32 / NX32 / NX32L

Firmware version:

1.00 / 1.00.00


The semWait() function will perform a traditional WAIT operation on the specified semaphore.

The semWait() mechanism will:

When the semaphore value>0, it will decrement the semaphore value and the calling thread will continue to execute.

When the semaphore value=0, it will block the calling thread on a FIFO queue waiting for another thread to call semSignal().

 

The semaphore mechanism can be used for a big range of different synchronization tasks. It can also be used to implement critical sections, like the Mutex mechanism, but for that purpose the Mutex is better suited.

The semWait() operation also offers a timeout facility to reduce the time waiting for the semaphore.

 

Also see the section on thread synchronization for more information.

 

 

Input:

sem : SEMAPHORE

The semaphore to wait for.                

 

timeout : INT (default: -1 forever)

The time, in ms., to wait for the semaphore to be signaled.

Use -1 to wait forever. This is the default.

 

Returns: INT

0

Success.

1

Semaphore is not initialized.

2

Timeout occurred. (operation aborted).

 

Declaration:

FUNCTION semWait : INT;
VAR_INPUT
   sem     : SEMAPHORE;
   timeout : INT := -1;
END_VAR;

 

 

Example:

INCLUDE rtcu.inc
 
VAR
   sem : SEMAPHORE;
END_VAR;
 
PROGRAM test;
   ...
   // Initialize Semaphore
   sem := semInit(initval:=3);
   IF semValue(sem:=sem) = -1 THEN DebugMsg(message:="sem failed to init!"); END_IF;
   ...
BEGIN
   ...
   // Wait until resource is free or timeout
   IF semWait(sem:=sem,timeout:=1000) = 0 THEN
      // Only do these actions if we have access to the resource
      ...
      // Free the resource after use
      semSignal(sem:=sem);
   END_IF;
   ...
END;
 
END_PROGRAM;