C 'Volatile' keyword in ISR and multithreaded program?

后端 未结 5 1313
Happy的楠姐
Happy的楠姐 2020-12-19 03:21

I read about usage of C volatile keyword in memory-mapped hardware register, ISR, and multithreaded program.

1) register

uint8_t volat         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 03:55

    The compiler is indeed to allow that nothing else changes your variables unless some every specific conditions are met. One of them is volatile access; others are certain compiler barriers.

    The naive way to program multithreaded code which you may have in mind is indeed prone to errors and would be considered undefined behaviour. If you have correct multithreaded code, then either an optimisation is still legal (like in your final task1, where the loop is still UB and may be thrown out), or the synchronisation primitives will contain the necessary barriers (usually in the guts of some atomic variables).

    To round things up, here's a corrected version of the multithreaded example:

     for (;;)
     {
         lock();
         if (var != 0) { unlock(); break; }
         unlock();
     }
    

    The implementation of the unlock() function introduces a compiler barrier which ensures that the loop cannot be optimized away.

提交回复
热议问题