是可变的分配和读取原子操作? [英] Is variable assignment and reading atomic operation?

查看:147
本文介绍了是可变的分配和读取原子操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到在任何单证参考这个...

I was unable to find any reference to this in the documentations...

时分配给一个双(或任何其它的简单类型,包括布尔值)的原子操作从线程的角度来看

Is assigning to a double (or any other simple type, including boolean) an atomic operation viewed from the perspective of threads?

double value = 0;

public void First() {
 while(true) {
  value = (new Random()).NextDouble();
 }
}

public void Second() {
 while(true) {
  Console.WriteLine(value);
 }
}

在此code样品,第一种方法称为在一个线程中,并且第二中另一个。第二种方法可以得到一个搞砸值,如果它分配期间得到其执行的变量在另一个线程?

In this code sample, first method is called in one thread, and the second in another. Can the second method get a messed up value if it gets its execution during assignment to the variable in another thread?

我不在乎,如果我收到的旧值,这是唯一重要的,以获得一个有效的值(并非出2出的8字节设置)。我知道这是一个愚蠢的问题,但我想可以肯定的,因为我不知道CLR实际上是怎样设置的变量。

I don't care if I receive the old value, it's only important to receive a valid value (not one where 2 out of 8 bytes are set). I know it's a stupid question, but I want to be sure, cause I don't know how CLR actually sets the variables.

推荐答案

要回答你的问题,没有。分配到双打不保证为是原子的。该文档可这里。基本上,&LT; = 32位内置类型是原子,> = 64位的类型都没有。有关64位类型的原子操作,您可以使用<一的方法href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx">System.Threading.Interlocked

To answer your question, no. Assignments to doubles are not guarenteed to be atomic. The docs are available here. Basically, <= 32-bit built-in types are atomic, >= 64-bit types aren't. For atomic operations on 64bit types, you can use the methods on System.Threading.Interlocked

这篇关于是可变的分配和读取原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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