zoukankan      html  css  js  c++  java
  • 模拟dispatch_once

    dispatch_once

     

    dispatch_once可以保证一段代码只被执行一次,因此出现之后使用最多的场景就是实现单例。本文来模拟实现dispatch_once的功能。

    模拟dispatch_once

    直接上代码

     1 static NSMutableDictionary 
     2 *lockMapping = nil;
     3 void do_once(int *predicate, void(^block)()){
     4     if(*predicate != -1){   
     5         NSLock *lock = nil;        
     6         @synchronized ([NSObject class]) { 
     7             NSLog(@"get lock");   
     8             if(lockMapping == nil){
     9                 lockMapping = [NSMutableDictionary dictionary];
    10             }            
    11             NSString *key = [NSString stringWithFormat:@"%p", predicate];     
    12             if(![lockMapping objectForKey:key]){
    13                 [lockMapping setObject:[[NSLock alloc] init] forKey:key];
    14             }
    15             
    16             lock = [lockMapping objectForKey:key];
    17         }
    18         
    19         [lock lock];        
    20         if(*predicate != -1){
    21             block();
    22             *predicate = -1;
    23         }
    24         
    25         [lock unlock];
    26     }
    27 }
    28  
    29 
    30 原理很简单,就不做过多解释了。使用:
    31 
    32  
    33 
    34 @interface Test : NSObject
    35  (instancetype)shareInstance;
    36  @end
    37 
    38 @implementation Test
    39 
    40  (instancetype)shareInstance{ 
    41     static int token;  
    42     static Test *t = nil;
    43     do_once(&token, ^{
    44         t = [[Test alloc] init];        
    45         NSLog(@"execute once");
    46     });    
    47     NSLog(@"execute every time");  
    48     return t;
    49 }@end

    测试:

    1 int main()
    2 {    for(int i = 0; i < 100; i++){
    3         dispatch_async(dispatch_queue_create(0, DISPATCH_QUEUE_CONCURRENT), ^{
    4             [Test shareInstance];
    5         });
    6     }    
    7     [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];    
    8     return 0;
    9 }
    
    

     

  • 相关阅读:
    UE4 多人模式
    UE4 r.ScreenPercentage 150 导致的画面只有丢失
    UE4 3D Widget渲染优先级最高
    UE4 VR中血条的做法 3d widget
    UE4 源码bug 蓝图节点CreateSession导致的崩溃
    UE4 小技巧
    ue4(转载) 在VR中的按钮 Button In VR
    ue4 可点击座舱实现 Clickable cockpit
    两种排序方法(选择排序和冒泡排序)
    特殊的Josn格式
  • 原文地址:https://www.cnblogs.com/fengmin/p/5541304.html
Copyright © 2011-2022 走看看