critical keyword

critical {...} Keyword Documentation

The critical keyword is used to denote a block of code that must be executed without interruption. This ensures that critical sections of code are executed as fast and effectively as possible, also the accuracy of delays is increased as no switching between different tasks is possible. Warning it is not recommended to stay in a critical section for a longer time, as processing of drivers and execution of messages is not possible while the critical section is executed.

Structure of the critical Block

The critical block is used to enclose code that must complete without being preempted:

Components:

  1. critical Keyword: Used to declare the start of a critical section.
  2. Code Block: The code within the curly braces {} is executed without interruptions.

Simple Example

Here’s a hypothetical example demonstrating the use of the critical block in a program:

// A speed test critical { // Start of critical section start = lib.time.getTime(0); //get current milliseconds running

for(i=0,i<10000,i+=1) drv.digitalIO.toggle();

millis = lb.time.getTime(0) -start; // End of critical section };

lib.log(“Execution took “+millis+ “ ms”);

Explanation:

  • Speed Test: Assumes a test for the highest possible toggling speed of a pin using Tipcontrol.

Practical Use

  • Concurrency Control: Even tough variables in TipControl are thread safe, if you need concurrent operations on the same variable, which is also accessed by paralel code you might need critical.
  • Real-time Systems: Ensure time-critical operations are completed without preemption in real-time systems.

Considerations

  • Blocking Nature: Code inside a critical block will block other threads , so make the code as brief as possible to minimize impact on system responsiveness.
  • Deadlock: Be cautious when using critical sections , endless loops within critical section can completly block the execution of the TipControl system.