线程同步会减慢多线程应用程序的速度
我有一个用 C# 编写的多线程应用程序。我注意到,使用 lock(this) 方法实现线程同步会使应用程序减慢 20%。这是预期的行为还是我应该仔细研究实现?
I have a multithreaded application written in c#. What i noticed is that implementing thread synchronization with lock(this) method slows down the application by 20%. Is that an expected behavior or should i look into the implementation closer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 Windows 中监视性能计数器以了解需要多长时间您的应用程序花费在争夺锁上。
There are performance counters you can monitor in Windows to see how much time your application spends contending for locks.
锁定确实会增加一些开销,这是无法避免的。您的某些线程现在也很可能正在等待资源被释放,而不是在需要时才获取它们。如果你正确地实现了线程同步,那么这是一件好事。
但一般来说,如果不深入了解该应用程序,就无法回答您的问题。 20% 的减速可能没问题,但您可能锁定得太宽泛,然后程序(通常)会变慢。
另外,请不要使用锁(this)。如果您的实例被传递而其他人锁定了引用,则会出现死锁。最佳实践是锁定其他人无法访问的私有对象。
Locking does add some overhead, that can't be avoided. It is also very likely that some of your threads now will be waiting on resources to be released, rather than just grabbing them when they feel like. If you implemented thread synchronization correctly, then that is a good thing.
But in general, your question can't be answered without intimate knowledge about the application. 20 % slowdown might be OK, but you might be locking too broadly, and then the program would (in general) be slower.
Also, please dont use lock(this). If your instance is passed around and someone else locks on the reference, you will have a deadlock. Best practice is to lock on a private object that noone else can access.
根据您的 lock() 语句的粗细程度,您确实可以影响 MT 应用程序的性能。只锁定您确实知道应该锁定的东西。
Depending on how coarse or granular your lock() statements are, you can indeed impact the performance of your MT app. Only lock things you really know are supposed to be locked.
任何同步都会减慢多线程速度。
话虽如此,
lock(this)
确实不是一个好主意。如果可能的话,您应该始终锁定仅用于同步的私有对象。确保将锁定保持在最低限度,并且保持锁定的时间尽可能短。这将有助于将“放缓”降至最低。
Any synchronization will slow down multithreading.
That being said,
lock(this)
is really never a good idea. You should always lock on a private object used for nothing but synchronization when possible.Make sure to keep your locking to a minimum, and only hold the lock for as short of a time as possible. This will help keep the "slowdown" to a minimum.