Middle+
Milleks kasutatakse programmeerimises võtmesõna volatile?
sobes.tech AI
Vastus AI-lt
volatile is used to indicate to the compiler and processor that the value of a variable can be changed by an independent execution thread or an external event relative to the current execution of the processor (for example, an input/output device).
Applications:
- Multithreading: Ensures that each time the variable is accessed, its value is read from the main memory and not from a processor register or cache. This prevents compiler optimizations that could lead to stale values in a multithreaded environment.
- Interaction with hardware: Used for variables that reflect the state of hardware registers or input/output ports, whose values can change unpredictably.
In Swift and Objective-C, volatile is used similarly to C/C++.
Example in C/Objective-C:
volatile int sharedFlag; // Shared variable accessible from different threads