iOS多线程梳理-GCD(3)

上一篇 iOS多线程梳理-GCD死锁

GCD栅栏函数

仅在自己创建的并发队列上有效,在全局(Global)并发队列、串行队列上,效果跟dispatch_(a)sync效果一样

我们有时需要异步执行两组操作,而且第一组操作执行完之后,才能开始执行第二组操作。这样我们就需要一个相当于栅栏一样的一个方法将两组异步执行的操作组给分割起来,当然这里的操作组里可以包含一个或多个任务。这就需要用到dispatch_barrier_async方法在两个操作组间形成栅栏。

    dispatch_queue_t concurrentQ = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"beagin %@",[NSThread currentThread]);
    dispatch_async(concurrentQ, ^{
        sleep(3);
        NSLog(@"first %@",[NSThread currentThread]);
    });
    dispatch_async(concurrentQ, ^{
        sleep(3);
        NSLog(@"section %@",[NSThread currentThread]);
    });
    dispatch_barrier_async(concurrentQ, ^{
        sleep(2);
        NSLog(@"barrier %@",[NSThread currentThread]);
    });
    dispatch_async(concurrentQ, ^{
        sleep(2);
        NSLog(@"three %@",[NSThread currentThread]);
    });
    dispatch_async(concurrentQ, ^{
        sleep(2);
        NSLog(@"four %@",[NSThread currentThread]);
    });
/*输出结果:    
  2017-10-10 22:02:42.083206+0800 GCDLearnAdvanced[8535:1603419] beagin {number = 1, name = main}
  2017-10-10 22:02:45.086151+0800 GCDLearnAdvanced[8535:1603466] section {number = 3, name = (null)}
  2017-10-10 22:02:45.086187+0800 GCDLearnAdvanced[8535:1603468] first {number = 4, name = (null)}
  2017-10-10 22:02:47.088121+0800 GCDLearnAdvanced[8535:1603466] barrier {number = 3, name = (null)}
  2017-10-10 22:02:49.089080+0800 GCDLearnAdvanced[8535:1603466] three {number = 3, name = (null)}
  2017-10-10 22:02:49.093410+0800 GCDLearnAdvanced[8535:1603468] four {number = 4, name = (null)}
*/

可以看到这个方法会阻塞这个queue(注意是阻塞 queue ,而不是阻塞当前线程),一直等到这个 queue 中排在它前面的任务都执行完成后才会开始执行自己,并且当自己 同步执行 完毕后,再会取消阻塞,使这个 queue 中排在它后面的任务继续执行。

GCD延时提交

    //创建串行队列
    dispatch_queue_t serialQ = dispatch_queue_create("serialQ", DISPATCH_QUEUE_SERIAL);                 
    NSLog(@"beagin %@",[NSThread currentThread]);
    dispatch_async(serialQ, ^{
        NSLog(@"task 开始 %@",[NSThread currentThread]);
        sleep(10);
        NSLog(@"task 完成 %@",[NSThread currentThread]);
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), serialQ, ^{
        NSLog(@"After...%@",[NSThread currentThread]);
        sleep(2);
        NSLog(@"After.22.%@",[NSThread currentThread]);
    });
/*输出结果:
 2017-10-12 15:11:27.109950+0800 GCDLearnAdvanced[2409:593908] beagin {number = 1, name = main}
 2017-10-12 15:11:27.110231+0800 GCDLearnAdvanced[2409:593956] task 开始 {number = 3, name = (null)}
 2017-10-12 15:11:37.114435+0800 GCDLearnAdvanced[2409:593956] task 完成 {number = 3, name = (null)}
 2017-10-12 15:11:37.114603+0800 GCDLearnAdvanced[2409:593956] After...{number = 3, name = (null)}
 2017-10-12 15:11:39.118761+0800 GCDLearnAdvanced[2409:593956] After.22.{number = 3, name = (null)}
*/

从打印输出可以看出,dispatch_after只是延时提交block,并不是延时后立即执行。所以想用dispatch_after精确控制运行状态的时候需要注意下

GCD dispatch_apply

    NSLog(@"beagin %@",[NSThread currentThread]);
    dispatch_apply(3, dispatch_get_global_queue(0, 0), ^(size_t index) {
        sleep(3);
        NSLog(@"current%@ %@",@(index),[NSThread currentThread]);
    });
    NSLog(@"end %@",[NSThread currentThread]);
    /*输出结果:
     2017-10-11 14:19:55.146699+0800 GCDLearnAdvanced[1728:463964] beagin {number = 1, name = main}
     2017-10-11 14:19:58.148147+0800 GCDLearnAdvanced[1728:463964] current0 {number = 1, name = main}
     2017-10-11 14:19:58.148168+0800 GCDLearnAdvanced[1728:464015] current1 {number = 3, name = (null)}
     2017-10-11 14:19:58.148185+0800 GCDLearnAdvanced[1728:464021] current2 {number = 4, name = (null)}
     2017-10-11 14:19:58.148291+0800 GCDLearnAdvanced[1728:463964] end {number = 1, name = main}
     */

从输出结果看出,beagin到end中间任务共耗时3s。所以当数组内元素需要循环处理且比较耗时可以使用这个函数

GCD Dispatch Source

定时器案例:

    NSLog(@"beagin %@",[NSThread currentThread]);
    __block NSInteger timeout = 3;
    dispatch_queue_t globalQ = dispatch_get_global_queue(0, 0);
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQ);
    dispatch_source_set_timer(source, dispatch_walltime(NULL,0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(source, ^{
        if (timeout<=0) {
            dispatch_source_cancel(source);
            NSLog(@"end %@",[NSThread currentThread]);
        }else{
            timeout --;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"现在秒 %@",@(timeout));
            });
        }
    });
    dispatch_resume(source);
   /*输出结果:
     2017-10-12 16:00:33.139472+0800 GCDLearnAdvanced[2717:646701] beagin {number = 1, name = main}
     2017-10-12 16:00:33.167203+0800 GCDLearnAdvanced[2717:646701] 现在秒 2
     2017-10-12 16:00:34.140082+0800 GCDLearnAdvanced[2717:646701] 现在秒 1
     2017-10-12 16:00:35.140850+0800 GCDLearnAdvanced[2717:646701] 现在秒 0
     2017-10-12 16:00:36.140079+0800 GCDLearnAdvanced[2717:646756] end {number = 3, name = (null)}
     */

关于 dispatch_walltime和dispatch_time 使用区别

进度条案例:

    dispatch_queue_t globalQ = dispatch_get_global_queue(0, 0);
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, globalQ);
    __block NSUInteger totalComplete = 0;
    dispatch_source_set_event_handler(source, ^{
        NSUInteger value = dispatch_source_get_data(source);
        totalComplete += value;
        NSLog(@"进度 %@ ",@((CGFloat)totalComplete/100));
    });
    dispatch_resume(source);
    for (NSInteger i=0; i<100; i++) {
        dispatch_async(globalQ, ^{
            dispatch_source_merge_data(source, 1);
            NSLog(@"线程:%@~~~~~~~~~~~~i = %@", [NSThread currentThread],@(i));
        });
    }
//输出结果: ---太长,就不上了

从打印上可以看到进度打印并不是随线程打印连续的显示,是间断的。原因:DISPATCH_SOURCE_TYPE_DATA_ADD是将触发结果相加,最后统一执行响应。如果dispatch_source_merge_data之间间隔时间越长,则每次触发都会响应,但是如果间隔的时间很短,则会将触发后的结果相加后统一触发。利用这一特性可以用来更新进度条,因为没必要每次进度触发都响应。

GCD只执行一次

//单例模式
static BaseViewController *instance;
+(instancetype)shareSingleMethod{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

dispatch_once_t必须是全局或static变量。其实就是保证dispatch_once_t只有一份实例

GCD信号量

//创建信号量,参数:信号量的初值,如果小于0则会返回NULL
dispatch_semaphore_create(信号量值)
//等待降低信号量
dispatch_semaphore_wait(信号量,等待时间)
//提高信号量
dispatch_semaphore_signal(信号量)

  • 信号量的工作原理:
    如果初始semaphore信号量的值 >= 1时:对semaphore计数进行减1,然后dispatch_semaphore_wait 函数返回。该函数所处线程就继续执行下面的语句。
    如果初始semaphore信号量的值 = 0时:那么就阻塞该函数所处的线程,阻塞时长为timeout指定的时间。如果阻塞时间内semaphore的值被dispatch_semaphore_signal函数加1了,该函数所处线程获得了信号量被唤醒。然后对semaphore计数进行减1并返回,继续向下执行。如果阻塞时间内没有获取到信号量唤醒线程或者信号量的值一直为0,那么就要等到指定的阻塞时间后,该函数所处线程才继续向下执行。

案例同步获取定位信息(以百度地图为例)

- (NSString *)getLocalLatAndLon{
    [_locService startUserLocationService];
    dispatch_async(dispatch_get_main_queue(), ^{
        hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.label.text = NSLocalizedString(@"正在获取最新位置...", @"HUD loading title");
    });
    semaphore = dispatch_semaphore_create(0);
    //信号量减1,如果>0,则向下执行,否则等待
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_async(dispatch_get_main_queue(), ^{
        [hud hideAnimated:YES];
    });
    _locService.delegate=nil;
    [_locService stopUserLocationService];
    return _localXY;
}
//百度定位代理
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    if (userLocation.location.coordinate.latitude!=0&&userLocation.location.coordinate.longitude!=0) {
        _localXY=[NSString stringWithFormat:@"%f,%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude];
        //信号量加1
        dispatch_semaphore_signal(semaphore);
    }
}

下一篇 iOS多线程梳理-NSOperation

你可能感兴趣的:(iOS多线程梳理-GCD(3))