zoukankan      html  css  js  c++  java
  • Grand Central Dispatch (GCD)

    1. 关于 dispatch_once

    dispatch_once

    Executes a block object once and only once for the lifetime of an application.
    在stackoverflow上有个对dispatch_once的解释,非常棒:

    What's the exact reason for using dispatch_once in the shared instance accessor of a singleton under ARC?

    +(MyClass*)sharedInstance
    {
    //  Static local predicate must be initialized to 0
        staticMyClass*sharedInstance = nil;
        staticdispatch_once_t onceToken =0;
        dispatch_once(&onceToken,^{
            sharedInstance =[[MyClass alloc] init];
        // Do any other initialisation stuff here
        });
        return sharedInstance;
    }   

    dispatch_once() is absolutely synchronous. Not all GCD methods do things asynchronously (case in point, dispatch_sync() is synchronous). The use of dispatch_once() replaces the following idiom:

    +(MyClass*)sharedInstance {
        staticMyClass*sharedInstance;
        @synchronized(self)
        {
            if(sharedInstance == nil)
            {
                sharedInstance =[[MyClass alloc] init];
            }
        }
        return sharedInstance;
    } 

    The benefit of dispatch_once() over this is that it's faster. It's also semantically cleaner, because the entire idea of dispatch_once() is "perform something once and only once", which is precisely what we're doing.

     

     

  • 相关阅读:
    About me
    新blog!!!
    卡常技巧
    考试策略
    Bzoj 1260: [CQOI2007]涂色paint (区间DP)
    Bzoj 1081 [Ahoi2009] chess 中国象棋
    NOIP2018 全国热身赛 第二场 (不开放)
    AT2386 Colorful Hats (乱搞题,思维题)
    模拟赛2
    CF873B Balanced Substring (前缀和)
  • 原文地址:https://www.cnblogs.com/whyandinside/p/3300795.html
Copyright © 2011-2022 走看看