浅谈对C# volatile关键字的理解
一、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.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.
The volatile keyword can be applied to fields of these types:
Reference types.
Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer to volatile."
Types such as sbyte, byte, short, ushort, int,

本文探讨了C#中的volatile关键字,旨在确保多线程环境下变量的一致性。volatile防止编译器优化导致的本地缓存,确保所有线程直接操作共享内存,从而保证变量的最新值可见性。
最低0.47元/天 解锁文章
1820

被折叠的 条评论
为什么被折叠?



