锁之间的区别(这)和静态对象的锁静态、区别、对象

2023-09-04 00:45:31 作者:夏初花未谢°

哪以下两个code片断的是更好地使用?

 静态只读对象_locker =新的对象();
锁(_locker)
 

 锁(本)
 

是当前实例的对象。那么,为什么是锁(_locker)总是在书?

  synchronized不能锁静态变量 面试官 请说一下对象锁和类锁的区别

相关:   What是(thisLock)锁(本)和锁定的区别?   为什么锁(本){…}?坏

解决方案

有可能是一个很大的区别。两者之间最大的区别在于,第一个例子使用一个单一的对象锁定(因此静态关键字),而在第二示例关键字意味着锁定上的一个实例。因此,有可能是从性能的角度,甚至从正确的角度有很大的区别,但是这取决于锁内code。

当你需要的是同步访问实例级别的字段,你不应该使用静态关键字,因为这将同步C本身的$ C $,而不是数据(这可能会导致不必要的性能损失)。当然,如果数据本身是静态(类级别的数据,而不是实例级别的数据),你需要使用静态关键字。在另一方面,当您使用关键字锁定,你所访问的共享/静态资源的同时,你会(当然)有一个正确的问题,因为同步的是一个实例的基础和多个实例仍然能够同时访问共享数据

和存在另外一个问题,但不同的是比用于previously注意到的差异小得多。第一个例子使用一个秘密申报对象锁定,而另一个使用了指针,这是引用的实例方法本身的对象。因为该参考文献是可公开访问的其他对象,有可能为他们在其上锁定,这可能导致在极少数情况下死锁。如果你是一个应用程序开发人员,我不会担心得多这个(只要你不上的事情锁定像 System.String 的System.Type ),但如果你是一个框架开发者,你当然不应该使用锁(本),因为没有办法告诉以何种方式应用程序开发人员(AB)使用code。

Which of the following two code snippets is better to use?

static readonly object _locker = new object();
lock (_locker)

or

lock (this)

this is an object of the current instance. So why is lock (_locker) always in the books?

Related: What is the difference between lock(this) and lock(thisLock)? Why is lock(this) {…} bad?

解决方案

There could be a big difference. The biggest difference between the two is that the first example uses a single object to lock on (hence the static keyword) while the this keyword in the second example implies locking on an instance. There could therefore be a big difference from a performance perspective and even from a correctness perspective, but that depends on the code inside the lock.

When all you need is to synchronize access to instance level fields, you should not use the static keyword, since that will synchronize the code itself, instead of the data (which could cause an unneeded performance hit). Of course, if the data itself is static (class level data instead of instance level data), you need to use the static keyword. On the other hand, when you use the this keyword to lock, while you're accessing shared / static resources, you will (of course) have a correctness problem, since synchronization is on an instance basis and multiple instance will still be able to access the shared data at the same time.

And there is another problem, but the difference is much smaller than for the previously noted differences. The first example uses a privately declared object to lock on, while the other uses the this pointer, which is the reference to the object of that instance method itself. Because this reference is publicly accessible to other objects, it is possible for them to lock on it, which could cause deadlocks in rare circumstances. If you're an application developer, I wouldn't worry to much about this (as long as you don't lock on things like System.String or System.Type), but if you are a framework developer, you should certainly not use lock(this), since there is no way to tell in what way application developers will (ab)use your code.