.NET多线程 - 我是否需要同步访问原始类型的变量? [英] .NET Multithreading - Do I need to synchronise access to a variable of primitive type?

查看:173
本文介绍了.NET多线程 - 我是否需要同步访问原始类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景

我有一类与布尔已启用属性,所使用的其他线程中循环,看它是否应该停止与否。这个想法是一个不同的线程可以将该属性设置为false,并阻止其他线程干净运行。<​​/ P>

问题

我应该懒得连载访问该已启用使用类似锁(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多线程 - 我是否需要同步访问原始类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆