_running (implicit variable)

Top  Previous  Next

The _running is an implicit BOOL variable that is automatically declared and handled by the system when a THREAD_BLOCK is declared.

The usage of the _running BOOL variable is to signal whether the thread is running or not. This can be used for checking if a thread has successfully started, as well as to catch an attempt where more threads than the system allows are started. It can also be used to synchronize with a thread that has stopped running after some condition has been met.

 

Consider this THREAD_BLOCK:

 

THREAD_BLOCK TEST;
VAR_INPUT
  stop : BOOL;
END_VAR;
  ...
END_THREAD_BLOCK;

 

 

The VPL compiler will automatically allocate a hidden variable named _running of the type BOOL in the VAR_OUTPUT section of the thread-block. It will also insert code that updates the status:

 

THREAD_BLOCK TEST;
VAR_INPUT
  stop : BOOL;
END_VAR;
VAR_OUTPUT
  _running : BOOL;                        <--- Automatically generated by the compiler.
END_VAR;
  ...
  _running:=FALSE;                        <--- Automatically generated by the compiler.
END_THREAD_BLOCK;

 

The assignment of FALSE to _running will be the very last operation done by the thread before it ceases.

 

When the TEST thread-block is instantiated, the updating of _running will again be done automatically:

 

PROGRAM abc;
VAR
  myTest : TEST;
END_VAR;
 
myTest();
myTest._running:=TRUE;                <--- Automatically generated by the compiler.
 
END_PROGRAM;

 

If the thread has successfully started, the myTest._running variable will be set to TRUE which indicates that the thread is running. If the thread failed to start, it will be set to FALSE by the system.

 

Its possible to dynamically terminate an active thread. This can be seen in the example below. The program creates and starts a thread, waits for 20 seconds, and then terminates the thread.

 

INCLUDE rtcu.inc
 
THREAD_BLOCK TEST;
VAR_INPUT
  stop : BOOL;
END_VAR;
 
WHILE NOT stop DO
  DebugMsg(message:="Working hard...");
  Sleep(delay:=1000);
END_WHILE;
 
END_THREAD_BLOCK;
 
 
PROGRAM abc;
VAR
  myTest : TEST;
END_VAR;
 
myTest(stop:=FALSE);
Sleep(delay:=20000);
myTest.stop:=TRUE;
WHILE myTest._running DO
  DebugMsg(message:="Waiting for TEST thread to terminate...");
  Sleep(delay:=1000);
END_WHILE;
 
END_PROGRAM;