gpt4 book ai didi

c# - C#中 'volatile'关键字的用途是什么

转载 作者:IT王子 更新时间:2023-10-29 04:52:12 24 4
gpt4 key购买 nike

C# 中 volatile 关键字的用途是什么?

我需要在哪里使用这个关键字?

我看到了下面的语句,但是我无法理解为什么这里需要volatile

internal volatile string UserName; 

最佳答案

请参阅规范的第 10.5.3 节,其中指出:

For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock-statement (§8.12). These optimizations can be performed by the compiler, by the run-time system, or by hardware. For volatile fields, such reordering optimizations are restricted:

A read of a volatile field is called a volatile read. A volatile read has “acquire semantics”; that is, it is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.

A write of a volatile field is called a volatile write. A volatile write has “release semantics”; that is, it is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.

These restrictions ensure that all threads will observe volatile writes performed by any other thread in the order in which they were performed. A conforming implementation is not required to provide a single total ordering of volatile writes as seen from all threads of execution.

如果您打算制作一个易变字段,请非常仔细地阅读。如果您没有完全彻底理解可变语义的所有含义,那么不要尝试使用它们。使用锁通常要好得多,它会自动为您提供足够的内存屏障以确保必要的获取和释放语义。请记住,锁只有在发生争用时才真正昂贵。

关于c# - C#中 'volatile'关键字的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4103415/

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