ios实用开发技巧iOS 开发 iOS 开发每天分享优质文章

iOS开发系列-多线程之GCD扫盲篇

2018-07-23  本文已影响119人  skylor

1.概念相关

2.队列任务组合方式

串行队列 + 异步执行log.png 全局队列 + 异步执行log.png 主队列 + 异步执行log.png 串行队列 + 同步执行log.png 并行队列 + 同步执行log.png 主队列 + 同步执行log(死锁).png

3.其它API

dispatch_queue_t mySerialQueue = dispatch_queue_create("com.helloWorld", NULL);
dispatch_queue_t myGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_set_target_queue(mySerialQueue, myGlobalQueue);// 第一个参数为需要修改优先级的队列,第二个为需要修改成什么样的队列
// 注意:第一个参数不可使用全局队列与主队列
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3ull * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^{
       
        NSLog(@"hello world");
    });
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
        NSLog(@"0");
    });
dispatch_group_async(group, queue, ^{
        NSLog(@"1");
    });
dispatch_group_async(group, queue, ^{
        NSLog(@"2");
    });
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"game over");
    });
执行结果如下:
0
1
2
game over
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("com.barrier", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading0");
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading1");
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading2");
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading3");
});

// 为保证读写的正确性,应在需要修改的代码插入dispatch_barrier,如下:
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("com.barrier", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading0");
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading1");
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading2");
});
dispatch_barrier_async(myConcurrentQueue, ^{
        NSLog(@"writing");
    });
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"reading3");
});

上一篇 下一篇

猜你喜欢

热点阅读