当使用“挥发性”或“Thread.MemoryBarrier()”中的线程锁定code? (C#) [英] When to use 'volatile' or 'Thread.MemoryBarrier()' in threadsafe locking code? (C#)

查看:188
本文介绍了当使用“挥发性”或“Thread.MemoryBarrier()”中的线程锁定code? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我应该使用挥发性/ Thread.MemoryBarrier()的线程安全?

When should I use volatile/Thread.MemoryBarrier() for thread safety?

推荐答案

您使用挥发性 / Thread.MemoryBarrier()当你想访问线程之间的变量,而不锁定。

You use volatile/Thread.MemoryBarrier() when you want to access a variable across threads without locking.

变量是原子,就像一个 INT 例如,始终读写整个一次。这意味着你将永远不会得到一半的价值的另一个线程改变了它和之后的另一半已经改变了。正因为如此,你可以安全地读取和写入在不同的线程的值而不syncronising。

Variables that are atomic, like an int for example, are always read and written whole at once. That means that you will never get half of the value before another thread changes it and the other half after it has changed. Because of that you can safely read and write the value in different threads without syncronising.

不过,编译器可以优化掉一些读取和写入,您prevent与挥发性关键字。比如你有一个这样的循环:

However, the compiler may optimize away some reads and writes, which you prevent with the volatile keyword. If you for example have a loop like this:

sum = 0;
foreach (int value in list) {
   sum += value;
}

编译器实际上可能计算的寄存器和只写值到变量在循环之后。如果您在变量挥发性,编译器将产生code读取和每一个写变变化,因此,它的值是向上在整个循环日期

The compiler may actually do the calculations in a processor register and only write the value to the sum variable after the loop. If you make the sum variable volatile, the compiler will generate code that reads and writes the variable for every change, so that it's value is up to date throughout the loop.

这篇关于当使用“挥发性”或“Thread.MemoryBarrier()”中的线程锁定code? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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