iOS开发之中级iOS DeveloperiOS程序猿

iOS开发多线程(GCD)

2017-04-22  本文已影响25人  asaBoat

相关概念

分析(线程任务)

dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"____");
    });
NSLog(@"-----1");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"-----3");
    });
    sleep(3);
    NSLog(@"-----2");
NSLog(@"-----1");
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"-----2");// 子线程
    });
    sleep(3);
    NSLog(@"-----3");
    NSLog(@"-----1");
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"-----2");//主线程
    });
    NSLog(@"-----3");
    sleep(3);
    NSLog(@"-----4");
dispatch_queue_t dispatchQueue = dispatch_queue_create("xin.queue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(dispatchQueue, ^{
        NSLog(@"currentThread,%@", [NSThread currentThread]); // 线程3
        [self openNewActionWithQue:dispatchQueue];
    });
- (void)openNewActionWithQue:(dispatch_queue_t)queue {
    NSLog(@"currentThread,%@", [NSThread currentThread]);线程3
    dispatch_sync(queue, ^{ // 发生死锁
        NSLog(@"currentThread,%@", [NSThread currentThread]);
    });
}

分析(dispatch_source_t)

看段代码

#import "TestViewController.h"

@interface TestViewController ()
@property(nonatomic,strong) dispatch_source_t timer;
@end
@implementation TestViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    __block NSInteger timeout = 10;//倒计总时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    __weak typeof(_timer) timer2 = _timer;
    dispatch_source_set_timer(timer2,dispatch_walltime(NULL, 0),1*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(timer2, ^{
        NSLog(@"%s",__func__);
        if(timeout<=0){ //倒计时结束,关闭
            dispatch_source_cancel(timer2);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
            });
            timeout-=1;
        }
    });
    dispatch_resume(_timer);
}
- (void)dealloc {
    NSLog(@"%s",__func__);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
上一篇 下一篇

猜你喜欢

热点阅读