应该都是全局变量是volatile限定? [英] Should ALL global variables be volatile-qualified?

查看:525
本文介绍了应该都是全局变量是volatile限定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,不正确需要 global_value 来声明挥发性

In this example, does correctness require global_value to be declared volatile?

int global_value = 0;

void foo () {
    ++ global_value;
}

void bar () {
    some_function (++global_value);
    foo ();
    some_function (++global_value);
}

我的理解是,挥发性是预期的的指针映射内存和变量可以通过信号被修改(并着重的的线程安全),但它很容易想象可能编译成这样的:

My understanding is that volatile is "intended" for pointers to mapped memory and variables which can be modified by signals (and emphatically not for thread-safety) but it's easy to imagine that bar might compile to something like this:

push EAX
mov EAX, global_value
inc EAX
push EAX
call some_function
call foo
inc EAX
push EAX
call some_function
mov global_value, EAX
pop EAX

这显然是不正确的,但即使没有挥发性我相信它是依照C抽象机是有效的。我错了或者是有效的?

This is clearly not correct, but even without volatile I believe it is valid according to the C abstract machine. Am I wrong or is it valid?

如果是这样,在我看来,挥发性是经常被忽视。这将是什么新鲜事

If so, it seems to me that volatile is routinely overlooked. This would be nothing new!

void baz (int* i) {
    some_function (++*i);
    foo ();
    some_function (++*i);
}

int main () {
    baz (&global_value);
}

即使保证编译成一个正确的不要缓存-global_value实施,将巴兹是类似正确的,或者是允许缓存的非易失性值 * I

Even if bar is guaranteed to compile into a correct dont-cache-global_value implementation, will baz be similarly correct, or is it allowed to cache the non-volatile value of *i?

推荐答案

没有,在挥发性关键词是没有必要在这里。由于 global_value 是函数外部可见,编译器不能假定它仍然是相同的,如果另一个函数被调用

No, the volatile keyword is not necessary here. Since global_value is visible outside the function bar, the compiler must not assume that it remains the same if another function is called.

[更新2011-07-28]我找到了一个不错的引证,证明这一切。它在ISO C99,5.1.2.3p2,对此我懒得全部复制到这里。它说:

[Update 2011-07-28] I found a nice citation that proves it all. It's in ISO C99, 5.1.2.3p2, which I am too lazy to copy here in its entirety. It says:

在被执行死刑序列中的某些特定点的序列点的,previous评估所有的副作用应完整及后续评估的无副作用不得发生。

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.

序列点包括:


  • 要一个函数的调用,后面的变量进行了评价(6.5.2.2)。

  • 一个完整的前pression的结束:[...]在离pression声明前pression(6.8.3); [...]

有你有你的证据。

这篇关于应该都是全局变量是volatile限定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆