对多种方法使用相同的锁 [英] Using the same lock for multiple methods
问题描述
到目前为止,使用多种方法使用同一锁没有任何问题,但我想知道以下代码是否可能确实存在我不知道的问题(性能?):
I haven't had any issues using the same lock for multiple methods so far, but I'm wondering if the following code might actually have issues (performance?) that I'm not aware of:
private static readonly object lockObj = new object();
public int GetValue1(int index)
{
lock(lockObj)
{
// Collection 1 read and/or write
}
}
public int GetValue2(int index)
{
lock(lockObj)
{
// Collection 2 read and/or write
}
}
public int GetValue3(int index)
{
lock(lockObj)
{
// Collection 3 read and/or write
}
}
这3种方法和集合都没有关联.
The 3 methods and the collections are not related in anyway.
此外,如果此lockObj
也被单例使用(在Instance属性中)会不会有问题?
In addition, will it be a problem if this lockObj
is also used by a singleton (in Instance property) ?
要澄清有关在Singleton类中使用相同的锁定对象的问题,
To clarify my question on using the same lock object in a Singleton class:
private static readonly object SyncObject = new object();
public static MySingleton Instance
{
get
{
lock (SyncObject)
{
if (_instance == null)
{
_instance = new MySingleton();
}
}
return _instance;
}
}
public int MyMethod()
{
lock (SyncObject)
{
// Read or write
}
}
这会引起问题吗?
推荐答案
如果您声明的方法不相关,则为每个方法使用不同的锁;否则效率低下(因为没有理由使用不同的方法来锁定同一对象,因为它们可以安全地并发执行).
If the methods are unrelated as you state, then use a different lock for each one; otherwise it's inefficient (since there's no reason for different methods to lock on the same object, as they could safely execute concurrently).
此外,似乎这些是锁定在静态对象上的实例方法-是故意的吗?我感觉那是个虫子;实例方法通常应该只锁定实例字段.
Also, it seems that these are instance methods locking on a static object -- was that intended? I have a feeling that's a bug; instance methods should (usually) only lock on instance fields.
关于Singleton设计模式:
Regarding the Singleton design pattern:
虽然锁定对于那些人来说是安全的,但更好的做法是对此类字段进行延迟初始化:
While locking can be safe for those, better practice is doing a delayed initialization of a field like this:
private static object sharedInstance;
public static object SharedInstance
{
get
{
if (sharedInstance == null)
Interlocked.CompareExchange(ref sharedInstance, new object(), null);
return sharedInstance;
}
}
这样,速度会更快一点(这是因为互锁的方法更快,并且因为初始化被延迟了),但是仍然是线程安全的.
This way it's a little bit faster (both because interlocked methods are faster, and because the initialization is delayed), but still thread-safe.
这篇关于对多种方法使用相同的锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!