title: How to ensure consistency of data between two execution loops
body: <p>I have been developing control software based on FreeRTOS operating system. From the timing point of view the software can be divided into two loops.</p>
  
  <p>The first execution loop (fast loop (FL)) is invoked with period 100 us at the end of analogue-digital conversion. The second execution loop (slow loop (SL)) is invoked after each fourth execution of fast loop. So the timing of the control software can be described by following timing diagram </p>
  
  <p><a href="https://i.stack.imgur.com/Q5EbK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5EbK.jpg" alt="enter image description here"></a></p>
  
  <p>I need to ensure consistency of data shared between fast and slow loop. The slow loop has to use during its whole execution time the data values valid at the end of fourth execution of the fast loop. </p>
  
  <p>I have been thinking about how to ensure the above mentioned consistency of data. My first idea is to use some global variable (let´s say <code>mutex</code>) </p>
  
  <pre><code>typedef enum
  {
      SLOW_LOOP_RUNNING,
      SLOW_LOOP_WAITING
  }MutexState
  
  MutexState mutex; 
  </code></pre>
  
  <p>which will be used in atomic manner. For example in case the slow loop starts its calculation it at first executes</p>
  
  <pre><code>mutex = SLOW_LOOP_RUNNING;
  </code></pre>
  
  <p>At the end of slow loop execution it executes</p>
  
  <pre><code>mutex = SLOW_LOOP_WAITING;
  </code></pre>
  
  <p>The fast loop monitors always the status of the <code>mutex</code> variable and in case it finds out that the mutex contains <code>SLOW_LOOP_RUNNING</code> value it doesn´t overwrite the shared variables. I think that this could work but I don´t like the global variable. Does anybody have better idea how to resolve that? Thanks in advance for any suggestions.</p>