命名为这种模式? (答案:延迟初始化具有双重检查锁定) [英] Name for this pattern? (Answer: lazy initialization with double-checked locking)

查看:115
本文介绍了命名为这种模式? (答案:延迟初始化具有双重检查锁定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

public class Foo
{
    private static object _lock = new object();

    public void NameDoesNotMatter()
    {
        if( SomeDataDoesNotExist() )
        {
            lock(_lock)
            {
                if( SomeDataDoesNotExist() )
                {
                    CreateSomeData();
                }
                else
                {
                    // someone else also noticed the lack of data.  We
                    // both contended for the lock.  The other guy won
                    // and created the data, so we no longer need to.
                    // But once he got out of the lock, we got in.
                    // There's nothing left to do.
                }
            }
        }
    }

    private bool SomeDataDoesNotExist()
    {
        // Note - this method must be thread-safe.
        throw new NotImplementedException();
    }

    private bool CreateSomeData()
    {
        // Note - This shouldn't need to be thread-safe
        throw new NotImplementedException();
    }
}



首先,有一些假设我需要状态:

First, there are some assumptions I need to state:


  1. 有一个很好的理由我不能只这样做一次一个应用程序的启动。也许数据尚未公布,等等。

  1. There is a good reason I couldn't just do this once an app startup. Maybe the data wasn't available yet, etc.

富可实例,并从两个或多个线程同时使用。我希望他们中的一个最终创造一些数据(而不是两者),那么我会同时允许访问相同的数据(忽略访问数据的线程安全)

Foo may be instantiated and used concurrently from two or more threads. I want one of them to end up creating some data (but not both of them) then I'll allow both to access that same data (ignore thread safety of accessing the data)

要SomeDataDoesNotExist()的成本并不大。

The cost to SomeDataDoesNotExist() is not huge.

现在,这并不必然必须局限于某些数据创建的情况,但是这是我能想到的一个例子。

Now, this doesn't necessarily have to be confined to some data creation situation, but this was an example I could think of.

这是我在识别作为一种模式是特别感兴趣的部分检查 - >锁 - >检查。我不得不解释这种模式有几次开发商谁没有乍一看得到算法,但然后才能欣赏它。

The part that I'm especially interested in identifying as a pattern is the check -> lock -> check. I've had to explain this pattern to developers on a few occasions who didn't get the algorithm at first glance but could then appreciate it.

不管怎样,其他人必须做人之道。这是一个标准化的模式呢?什么叫?

Anyway, other people must do similarly. Is this a standardized pattern? What's it called?

推荐答案

慵懒双重检查锁定初始化?

Lazy initialization with double-checked locking?

这篇关于命名为这种模式? (答案:延迟初始化具有双重检查锁定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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