非阻塞同步(MemoryBarrier)
我修改了非阻塞同步上给出的程序如下:
class DemoProg
{
int _answer;
bool _complete;
public void StartDemo()
{
Thread t1 = new Thread(A);
Thread t2 = new Thread(B);
t1.Start();
// Thread.Sleep(100); // To ensure that B is called after A.
t2.Start();
}
void A()
{
for (int i = 0; i < 1000000; i++)
_answer = 123;
Thread.MemoryBarrier(); // Barrier 1
_complete = true;
Thread.MemoryBarrier(); // Barrier 2
Console.WriteLine("Exiting A");
}
void B()
{
//Thread.Sleep(100);
Thread.MemoryBarrier(); // Barrier 3
if (_complete)
{
Thread.MemoryBarrier(); // Barrier 4
Console.WriteLine(_answer);
}
Console.WriteLine("Exiting B");
}
}
文章指出它们确保如果 B 在 A 之后运行,则读取 _complete 的结果将为 true。
>>>它们意味着记忆障碍。
即使我删除了内存障碍,输出也没有变化。 并且它并不能确保 if 条件结果为 true。
我是否以错误的方式解释了它?
谢谢。
I modified the program given on Non-Blocking Synchronization as following:
class DemoProg
{
int _answer;
bool _complete;
public void StartDemo()
{
Thread t1 = new Thread(A);
Thread t2 = new Thread(B);
t1.Start();
// Thread.Sleep(100); // To ensure that B is called after A.
t2.Start();
}
void A()
{
for (int i = 0; i < 1000000; i++)
_answer = 123;
Thread.MemoryBarrier(); // Barrier 1
_complete = true;
Thread.MemoryBarrier(); // Barrier 2
Console.WriteLine("Exiting A");
}
void B()
{
//Thread.Sleep(100);
Thread.MemoryBarrier(); // Barrier 3
if (_complete)
{
Thread.MemoryBarrier(); // Barrier 4
Console.WriteLine(_answer);
}
Console.WriteLine("Exiting B");
}
}
The article states that they ensure that if B ran after A, reading _complete would evaluate to true.
>> they means memory barriers.
Even if i remove memory barriers, there is no change in output. and it's not making sure that if condition results true.
did I interpret it in wrong way?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在此处和此处。
简而言之,作者是正确的。请密切关注该声明。特别要注意的是,作者说“如果 B 追随 A”。他并不是说条件总是评估为真。相反,该示例旨在演示内存障碍的一个特定细微差别。
此外,通过消除内存障碍来获得不同的结果将很难重现。造成这种情况的原因有很多。这可能是由于您运行测试的环境造成的。
I talk about this very example here and here.
In a nutshell, the author is correct. Pay very close attention to the statement. In particular, notice that the author says "if B ran after A". He was not saying that the condition will always evaluate true. Instead, the example was contrived to demonstrate one particular nuance of memory barriers.
Furthermore, getting a different result by removing memory barriers will be difficult to reproduce. There are many reasons for this. It is likely due to the environment in which you were running the tests.