使用相同的锁muliple方法 [英] Using the same lock for muliple methods

查看:197
本文介绍了使用相同的锁muliple方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有使用相同的锁多种方法至今的所有问题,但我想知道如果下面的code可能确实有问题,我不知道(性能):

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 也使用一个单(在实例属性)?

In addition, will it be a problem if this lockObj is also used by a singleton (in Instance property) ?

编辑:澄清我的问题上使用相同的锁定对象的单例类:

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
      }  
}

请问这样会导致问题?

Will this cause issues ?

感谢

推荐答案

如果该方法是不相关的,你的状态,然后用不同的锁,每一个;否则,它的效率不高(因为没有理由不同的方法对同一个对象的锁,因为他们可以安全地并发执行)。

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.

这篇关于使用相同的锁muliple方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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