需求:
批量执行一些任务的时候,可以有其他任务插进来优先执行,待执行完插队的任务后,继续执行之前的任务。
代码:
//
// ViewController.m
// GCD插队的任务
//
// Created by 秦伟 on 2017/4/21.
// Copyright © 2017年 秦伟. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_queue_t low;
@property (nonatomic, strong) dispatch_queue_t high;
- (IBAction)buttonAction:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_low = dispatch_queue_create("com.test.low", DISPATCH_QUEUE_SERIAL);
_high = dispatch_queue_create("com.test.high", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(_low, _high);
for (NSInteger i = 0; i < 20; i++) {
dispatch_async(_low, ^{
[NSThread sleepForTimeInterval:1.0];
NSLog(@"low: %ld", i);
});
}
dispatch_async(_low, ^{
NSLog(@"全部完成!");
});
}
- (IBAction)buttonAction:(id)sender {
dispatch_suspend(_low);
dispatch_async(_high,^{
NSLog(@"high: 插!!!");
dispatch_resume(_low);
});
}
@end
网友评论