gpt4 book ai didi

c# - Volatile 违反了它的主要工作?

转载 作者:IT王子 更新时间:2023-10-29 04:27:23 25 4
gpt4 key购买 nike

根据 MSDN :

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

请注意最后一句:

这可确保字段中始终显示最新值。

但是,这个关键字有问题。

我已经 read它可以改变指令的顺序:

First instruction       Second instruction         Can they be swapped?
Read Read No
Read Write No
Write Write No
Write Read Yes! <----

这意味着 John 给一个 volatile 字段设置了一个值,later Paul 想要读取这个字段,保罗正在获取值!

这是怎么回事?这不是主要工作吗?

我知道还有其他解决方案,但我的问题是关于 volatile 关键字。

我(作为程序员)是否应该因为这种奇怪的行为而需要阻止使用此关键字?

最佳答案

嗯,你是对的。在 Joseph Albahari threading book/article 中有更详细的阐述.

The MSDN documentation states that use of the volatile keyword ensures that the most up-to-date value is present in the field at all times. This is incorrect, since as we’ve seen, a write followed by a read can be reordered.

http://www.albahari.com/threading/part4.aspx#_The_volatile_keyword

Should I ( as a programmer ) need to prevent using this keyword-because of such weird behavior?

只有在知道这种奇怪的行为后才能使用它。它不应该用作 Magic 关键字以在多线程环境中始终检索最新值。

IMO,应避免使用 volatile 关键字,因为很难找出可能的错误。

关于c# - Volatile 违反了它的主要工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com