具有释放/获取语义的 volatile [英] volatile with release/acquire semantics

查看:26
本文介绍了具有释放/获取语义的 volatile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Java 5 开始,volatile 关键字具有释放/获取语义,以使其他线程可以看到副作用(包括对 非 volatile 变量的赋值!).以这两个变量为例:

Since Java 5, the volatile keyword has release/acquire semantics to make side-effects visible to other threads (including assignments to non-volatile variables!). Take these two variables, for example:

int i;
volatile int v;

请注意,i 是一个常规的非易失性变量.想象线程 1 执行以下语句:

Note that i is a regular, non-volatile variable. Imagine thread 1 executing the following statements:

i = 42;
v = 0;

在稍后的某个时间点,线程 2 执行以下语句:

At some later point in time, thread 2 executes the following statements:

int some_local_variable = v;
print(i);

根据Java内存模型,在线程1写入v,然后在线程2读取v确保线程2看到对i 在线程 1 中执行,因此打印值 42.

According to the Java memory model, the write of v in thread 1 followed by the read of v in thread 2 ensures that thread 2 sees the write to i executed in thread 1, so the value 42 is printed.

我的问题是:volatile 在 C# 中是否具有相同的发布/获取语义?

My question is: does volatile have the same release/acquire semantics in C#?

推荐答案

C# 中volatile"的语义在规范的 3.10 和 10.4.3 节中定义.与其在此处重现它们,我鼓励您在规范中查找它,然后确定使用易失性"太复杂和危险,然后返回使用锁.这就是我一直在做的事情.

The semantics of "volatile" in C# are defined in sections 3.10 and 10.4.3 of the specification. Rather than reproduce them here, I encourage you to look it up in the spec, and then decide that it is too complicated and dangerous to use "volatile", and go back to using locks. That's what I always do.

请参阅3.10 执行顺序10.4.3 易失性字段规范.

这篇关于具有释放/获取语义的 volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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