iOS-GCD常用函式和柵欄函式

weixin_34162695發表於2018-06-30

GCD常用函式

//  ViewController.m
//  4.16-GCD常用函式
//
//  Created by 裴鐸 on 2018/4/16.
//  Copyright © 2018年 裴鐸. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self once];
}
/** 延期函式 */
- (void)delay{
    
    //為例驗證 列印開始時間
    NSLog(@"start");
    
    //1./延時執行的方法
    [self performSelector:@selector(task) withObject:nil afterDelay:2.0];
    
    //2./延時執行的方法 最後一個引數是:是否重複
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:NO];
    
    //3./延時執行的方法GCD
    //dispatch_queue_t queue = dispatch_get_main_queue();
    //獲取全域性併發佇列 預設的優先順序
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    /**
     引數
     1./重什麼時間開始延遲 DISPATCH_TIME_NOW現在 DISPATCH_TIME_FOREVER未來
     2./延遲多少時間(delayInSeconds) 填寫秒數 * 1000000000納秒(NSEC_PER_SEC)GCD中時間是以納秒計算
     3./在哪一個佇列中執行 dispatch_get_main_queue() 可以是子執行緒 這個是別的方法沒有的
     4./填寫要執行的任務
     想讓延遲任務在子執行緒中執行只傳入一個併發佇列就可以了
     */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
        //在這個block中寫要執行的任務
        NSLog(@"當前執行緒:%@ 任務:%s",[NSThread currentThread],__func__);
    });
}
/** 一次性程式碼
 整個應用程式的生命週期中只會執行一次的
 一次性帶麼不能放在懶載入中使用,用了你第二次取值時就為空了
 一次性程式碼主要用在單利模式中 並且 是檢查執行緒安全的(原子性)*/
- (void)once{
    NSLog(@"%s",__func__);
   
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"__once__");
    });
}
/** 任務 */
- (void)task{
    
    NSLog(@"當前執行緒:%@ 任務:%s",[NSThread currentThread],__func__);
}
@end

GCD柵欄函式

//  ViewController.m
//  4.16-GCD柵欄函式
//
//  Created by 裴鐸 on 2018/4/16.
//  Copyright © 2018年 裴鐸. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //獲得一個預設優先順序的全域性併發佇列
    //dispatch_queue_t queue = dispatch_get_global_queue(0, 0  );
    //如果有柵欄函式的話必須使用自己建立的併發佇列
    dispatch_queue_t queue = dispatch_queue_create("peiDuo", DISPATCH_QUEUE_CONCURRENT);
    //建立非同步函式
    dispatch_async(queue, ^{
        NSLog(@"           任務1:%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"           任務2:%@",[NSThread currentThread]);
    });
    
    //建立一個柵欄函式 柵欄函式之前的任務併發執行,完成後執行柵欄任務,完成後併發執行柵欄函式之後的任務
    dispatch_barrier_async(queue, ^{
        
        NSLog(@"           ++++++++++++++++ 這是一個柵欄 +++++++++++++++");
    });
    
    dispatch_async(queue, ^{
        NSLog(@"           任務3:%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"           任務4:%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"           任務5:%@",[NSThread currentThread]);
    });
}
@end

相關文章