volatile的用法

volatile是一个关于优化的关键字,目的是告诉编译器每次都要去读变量本身的值,而不是简单的将其优化为一个已知的值。

Volatile const int a = 10;

表示a是一个整形的常量,代码中不应该去修改它,但是它可以被外部修改,比如中断等

lcl:

 volatile是一个关于优化的关键字,目的是告诉编译器每次都要去读变量本身的值,而不是简单地将其优化为一个已知的值。

  volatile const int a = 10;

  表示a 是一个整形的常量,代码中不应该去修改它,但是它可以被外部修改,比如中断等

  比较易于理解的解释:

  “volatile的本意是“易变的”,volatile关键字是一种类型修饰符,用它声明的类型变量表示可以被某些编译器未知的因素更改,比如操作系统、硬件或者其它线程等。遇到这个关键字声明的变量,编译器对访问该变量的代码就不再进行优化,从而可以提供对特殊地址的稳定访问。

当要求使用volatile 声明的变量的值的时候,系统总是重新从它所在的内存读取数据,即使它前面的指令刚刚从该处读取过数据。而且读取的数据立刻被寄存

    参考网站:http://stackoverflow.com/questions/4437527/why-do-we-use-volatile-keyword-in-c

                          http://freestyler.pixnet.net/blog/post/23872864-c-c%2B%2B%E4%B8%AD%E7%9A%84volatile%E4%BD%BF%E7%94%A8%E6%99%82%E6%A9%9F%3F

                          http://blog.csdn.net/wuliming_sc/article/details/3717017

                          http://stackoverflow.com/questions/16259939/const-volatile-register-volatile-static-volatile-in-c

    附录:

    Consider this code,

int some_int = 100;

 

while(some_int == 100)

{

   //yourcode

}

When this program getscompiled, the compiler may optimize this code, if it finds that the program neverever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int== 100) to simply while(true) so that the execution could be fast (sincethe condition in while loop appears to be true always). (if the compiler doesn't optimizeit, then it has to fetch the value of some_int (if it's not loaded on a register) andcompare it with 100, each time which obviously is a little bit slow.)

However, sometimes,optimization (of some parts of your program) may be undesirable, becauseit may be that someone else is changing the value of some_int from outside the program which compiler isnot aware of, since it can't see it; but it's how you've designed it. Inthat case, compiler's optimization would not produce the desired result!

So, to ensure thedesired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays it's role. All you need to dois this,

volatile intsome_int = 100; //notethe 'volatile' qualifier now!


In others words Iwould explain this as follows:

volatile tells the compiler that, 

"Heycompiler, I'm volatile and, you know, I can be changed by some XYZ that you'renot even aware of. That XYZ could be anything. Maybe some alien outside thisplanet called program. Maybe some lighting, some form of interrupt, volcanoes,etc can mutate me. Maybe. You never know who is going to change me! So O youignorant, stop playing an all-knowing god, and don't dare touch the code whereI'm present. Okay?"

Well, that is how volatile prevents compiler from optimizing code. Nowgoogle it to see some sample examples.


Quoting from the C++Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementationto avoid aggressive optimization involving the object because the valueof the object might be changed by means undetectable by an implementation.[...]


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用volatile关键字,只需要在声明变量时在其前面加上volatile修饰符即可。volatile关键字用于修饰变量,以确保每次读取该变量时都是从主内存中获取最新的值,而不是从本地线程缓存中获取。这样可以保证多个线程能够正确地看到该变量的最新值。 需要注意的是,volatile关键字只能保证变量的可见性,无法保证操作的原子性。如果需要保证操作的原子性,可以使用synchronized关键字或其他原子性操作类,如AtomicInteger。 以下是一个使用volatile关键字的示例代码: public class MyThread implements Runnable { private volatile boolean flag = false; public void run() { while (!flag) { // 执行某些操作 } } public void stop() { flag = true; } } 在上述代码中,flag变量被声明为volatile类型。在MyThread线程中,通过不断地检查flag的值来决定是否继续执行。当stop方法被调用时,将flag设置为true,从而使得MyThread线程能够感知到这个变化并退出循环。 总结起来,使用volatile关键字可以保证变量的可见性,但不能保证操作的原子性。对于需要保证操作的原子性的情况,可以考虑使用synchronized关键字或其他原子性操作类。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [volatile用法](https://blog.csdn.net/qq_31452291/article/details/119239182)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [volatile详解](https://blog.csdn.net/weixin_43899792/article/details/124492448)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值