mxLock (Function)

Top  Previous  Next

Architecture:

X32 / NX32 / NX32L

Device support:

ALL

Firmware version:

1.00 / 1.00.00


The mxLock() function will lock the specified MUTEX variable.

This mutex mechanism ensures that only one thread will continue to run between the call to mxLock() and mxUnlock(). If the mutex is already locked, the calling thread will be blocked on a FIFO waiting queue until the current owner of the mutex calls mxUnlock(). If the owner of the mutex calls mxLock() several times, it will not block, but the number of mxLock() and mxUnlock() called must balance, and the mutex will not be released before the last and closing call to mxUnlock() is performed.

 

The mutex mechanism is traditionally used for implementing critical sections. Also see the section on thread synchronization for more information.

 

 

Input:

mx : MUTEX

The MUTEX to lock.                

 

Returns: INT

0

Mutex is locked.

1

Mutex is not initialized.

 

Declaration:

FUNCTION mxLock : INT;
VAR_INPUT
  mx : MUTEX;
END_VAR;

 

 

Example:

INCLUDE rtcu.inc
 
VAR
  mxCnt : MUTEX;
  Count : DINT := 0;
END_VAR;
 
THREAD_BLOCK Thread_A;
WHILE TRUE DO
  mxLock(mx:=mxCnt);
  Count := Count + 1;
  mxUnlock(mx:=mxCnt);
END_WHILE;
END_THREAD_BLOCK;
 
THREAD_BLOCK Thread_B;
WHILE TRUE DO
  mxLock(mx:=mxCnt);
  Count := Count + 5;
  mxUnlock(mx:=mxCnt);
END_WHILE;
END_THREAD_BLOCK;
 
PROGRAM test;
VAR
  TA   : Thread_A;
  TB   : Thread_B;
  i     : INT;
END_VAR;
 
mxCnt := mxInit();
 
TA();
TB();
 
BEGIN
  Sleep(delay:=1000);
  DebugFmt(message:="Count: \4",v4:=Count);
END;
 
END_PROGRAM;