Do you know the keyword volatile in C language?

Source: Internet
Author: User

When learning 32 keywords in C language, we don't pay much attention to the volatile keyword. Volatile is a type modifier. Volatile is "changeable" in Chinese ". InProgramUnder what circumstances should we use him? We often see the use of this keyword when analyzing the kernel. Example:

 
Struct task_struct {volatile long state;/*-1 unrunnable, 0 runnable,> 0 stopped */void * stack; atomic_t usage; unsigned int flags;/* per process flags, defined below */unsigned int ptrace ;.......

In applications, volatile is mainly designed to modify variables accessed and modified by different threads.

The volatile variable indicates that this variable mayChanged unexpectedlyTherefore, the compiler should not be optimized accordingly. Precisely, the optimizer must carefully re-read the value of this variable every time when using this variable, rather than using the backup stored in the register.

For example:

Extern int A; // Statement 1 Suppose A is a global variable.

......

Int B = A; // Statement 2

Int c = A; // Statement 3

 

Statement 2 and 3 both use the value of A. When the optimizer references the value of A in Statement 3, it is assumed that the value of a has been read to the Register in statement 2, in addition, A is not modified between Statement 2 and Statement 3. Therefore, it is unnecessary to read the value of A in the memory. Therefore, the value in the register is used directly. However, if the interrupt occurs before Statement 3 is executed, the interrupt happens to modify. The value obtained from Statement 3 is incorrect.

If the above global variable A is modified to volatile, the optimizer cannot optimize Statement 3 and re-value it in the memory.

 

As an Embedded System Programmer, volatile must know how to use it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.