Which scenes keyword “volatile” is needed to declare in objective-c?

后端 未结 3 979
无人及你
无人及你 2021-01-31 11:55

As i know, volatile is usually used to prevent unexpected compile optimization during some hardware operations. But which scenes volatile should be dec

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 12:09

    A good explanation is given here: Understanding “volatile” qualifier in C

    The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.

    Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object. So the simple question is, how can value of a variable change in such a way that compiler cannot predict. Consider the following cases for answer to this question.

    1) Global variables modified by an interrupt service routine outside the scope: For example, a global variable can represent a data port (usually global pointer referred as memory mapped IO) which will be updated dynamically. The code reading data port must be declared as volatile in order to fetch latest data available at the port. Failing to declare variable as volatile, the compiler will optimize the code in such a way that it will read the port only once and keeps using the same value in a temporary register to speed up the program (speed optimization). In general, an ISR used to update these data port when there is an interrupt due to availability of new data

    2) Global variables within a multi-threaded application: There are multiple ways for threads communication, viz, message passing, shared memory, mail boxes, etc. A global variable is weak form of shared memory. When two threads sharing information via global variable, they need to be qualified with volatile. Since threads run asynchronously, any update of global variable due to one thread should be fetched freshly by another consumer thread. Compiler can read the global variable and can place them in temporary variable of current thread context. To nullify the effect of compiler optimizations, such global variables to be qualified as volatile

    If we do not use volatile qualifier, the following problems may arise
    1) Code may not work as expected when optimization is turned on.
    2) Code may not work as expected when interrupts are enabled and used.

提交回复
热议问题