.NET多线程 - 我是否需要同步访问原始类型的变量?变量、多线程、原始、类型

2023-09-04 08:42:53 作者:青楼满座骚逼贱货

场景

我有一类与布尔已启用属性,所使用的其他线程中循环,看它是否应该停止与否。这个想法是一个不同的线程可以将该属性设置为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.