问题描述
场景
我有一类与布尔已启用
属性,所使用的其他线程中循环,看它是否应该停止与否。这个想法是一个不同的线程可以将该属性设置为false,并阻止其他线程干净运行。
问题
我应该懒得连载访问该已启用
使用类似锁(lockObject)属性{...}
,或者是它的安全不?
原始类型的读取,但原子只要他们读了CPU内适合。因此,读了32位基本类型是原子在32位CPU,而读取一个64位的类型不是。但是,除非它也是挥发性
您的其他线程可能不会看到由于缓存的变化。
The scenario
I have a class with a bool Enabled
property, that is used by a loop on another thread to see whether it should stop or not. The idea is that a different thread can set that property to false and stop the other thread running cleanly.
The question
Should I bother to serialise access to that Enabled
property using something like lock (lockObject) { ... }
, or is it safe without?
Primitive type reads are atomic provided that they fit within a CPU read. Thus a 32 bit primitive type read is atomic on a 32 bit CPU, whereas a 64 bit type read is not. However, unless it is also volatile
your other thread may not see changes due to caching.
这篇关于.NET多线程 - 我是否需要同步访问原始类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!