互锁是否提供所有线程的可见性? [英] Does Interlocked provide visibility in all threads?

查看:91
本文介绍了互锁是否提供所有线程的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个变量"counter",并且有多个线程通过使用互锁来访问和设置"counter"的值,即:

Suppose I have a variable "counter", and there are several threads accessing and setting the value of "counter" by using Interlocked, i.e.:

int value = Interlocked.Increment(ref counter);

int value = Interlocked.Decrement(ref counter);

我可以假设Interlocked所做的更改在所有线程中都是可见的吗?

Can I assume that, the change made by Interlocked will be visible in all threads?

如果没有,我该怎么做才能使所有线程同步变量?

If not, what should I do to make all threads synchronize the variable?

有人建议我使用volatile.但是,当我将计数器"设置为易失性时,编译器警告对易失性字段的引用将不被视为易失性".

someone suggested me to use volatile. But when I set the "counter" as volatile, there is compiler warning "reference to volatile field will not be treated as volatile".

当我阅读在线帮助时,它说:通常不应该使用ref或out参数传递一个易失字段".

When I read online help, it said, "A volatile field should not normally be passed using a ref or out parameter".

推荐答案

x86 CPU上的InterlockedIncrement/Decrement(x86的锁添加/dec)正在自动创建内存屏障,该屏障为所有线程提供可见性(即,所有线程都可以按顺序查看其更新,例如顺序内存一致性).内存屏障使所有待处理的内存加载/存储得以完成.尽管C#和Java(以及某些C/C ++编译器)强制使用volatile来限制内存,但volatile与该问题无关.但是,联锁操作已经受到CPU的内存限制.

InterlockedIncrement/Decrement on x86 CPUs (x86's lock add/dec) are automatically creating memory barrier which gives visibility to all threads (i.e., all threads can see its update as in-order, like sequential memory consistency). Memory barrier makes all pending memory loads/stores to be completed. volatile is not related to this question although C# and Java (and some C/C++ compilers) enforce volatile to make memory barrier. But, interlocked operation already has memory barrier by CPU.

也请看看我的另一个答案在stackoverflow中.

Please also take a look my another answer in stackoverflow.

请注意,我已经假设C#的InterlockedIncrement/Decrement是对x86的锁的add/dec的固有映射.

Note that I have assume that C#'s InterlockedIncrement/Decrement are intrinsic mapping to x86's lock add/dec.

这篇关于互锁是否提供所有线程的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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