何时在.NET中使用锁与MemoryBarrier [英] When to use lock vs MemoryBarrier in .NET

查看:69
本文介绍了何时在.NET中使用锁与MemoryBarrier的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,lock关键字是Monitor.EnterMonitor.Exit周围的语法糖,因此您可以说这段代码

lock(locker)
{
  // Do something
}

相同

Monitor.Enter(locker);
try
{
  // Do Something
}
finally
{
  Monitor.Exit(locker);
}

但是.NET框架还包括MemoryBarrier类,该类以类似的方式工作

Thread.MemoryBarrier();
//Do something
Thread.MemoryBarrier();

我很困惑,因为我想在lock/Monitor版本上使用Thread.MemoryBarrier? 线程教程使我更加困惑,该线程说明它们的功能相同. /p>

据我所见,可见的区别是不需要锁定对象,我猜想使用Monitor可以跨MemoryBarrier在单个线程上的线程进行某些操作.

我的直觉告诉我,MemoryBarrier的另一个主要区别是仅适用于变量而不适用于方法.

最后,这与现有问题无关,因为那是我理解其用法的volatile关键字.

在我看来,您几乎从不使用Thread.MemoryBarrier.它用于无锁代码-确保在一个线程上所做的更改对另一线程可见,而不会产生锁定成本.与lock不同,它不会控制线程同步.我看不出他在Joe的教程中说MemoryBarrierlock功能相同".您能解释一下您究竟从何处获得这种印象吗?

在我看来,除了主要熟练于并发的开发人员外,几乎对于任何人来说,低级无锁代码都太困难了.如果我想编写一些无锁代码,我将使用由那些开发人员(例如.NET 4.0中的Parallel Extensions) built 构建的更高级别的构建基块,而不是尝试自己编写. >

仅作为示例,我最近对volatile的确切含义睁开了眼睛,不是总是从主存储器读取,总是直接写入主存储器". (目前,我自己的线程教程仍具有该解释-我需要在某些时候进行修复.)a Threading Tutorial which states they function tthe same.

As far as I can see the visible difference is not needing a locking object, which I guess that using Monitor you could do something across threads where MemoryBarrier is on a single thread.

My gut is telling me that another key difference is MemoryBarrier is for variables only and not for methods.

Lastly this is not related to the existing question When to use ‘volatile’ or ‘Thread.MemoryBarrier()’ in threadsafe locking code? (C#), as that is focusing on the volatile keyword which I understand its usage of.

解决方案

In my view you should almost never use Thread.MemoryBarrier. This is used for lock-free code - making sure that changes made on one thread are visible to another without incurring the cost of a lock. It does not control thread synchronization, unlike lock. I don't see where in Joe's tutorial he says that MemoryBarrier "functions the same" as lock. Could you explain where exactly you're getting that impression from?

In my view, low level lock-free code is too difficult for almost anyone other than developers whose main proficiency is concurrency. If I want to write some lock-free code, I'll use higher level building blocks built by those developers (such as Parallel Extensions in .NET 4.0) rather than trying to roll my own.

Just as an example, I recently had my eyes opened to the precise meaning of volatile which isn't "always read from main memory, always write directly to main memory". (My own threading tutorial still has that explanation at the moment - something I need to fix at some point.) It's far more subtle than that. This means that some of my previous uses of volatile may well be incorrect.

这篇关于何时在.NET中使用锁与MemoryBarrier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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