美文网首页
GCD相关基础知识

GCD相关基础知识

作者: MrOreo | 来源:发表于2017-10-24 12:32 被阅读0次
    我看世界
    原创文章,转载请注明:转自:Try_Try_Try

    1.获取Dispatch Queue 的两种方法

    • 方法一: 通过GCD api 生成队列dispatch_queue_create
      // 串行队列
        dispatch_queue_t mySerialDispatchQueue = dispatch_queue_create("com.example.gcd.MySerialDispatchQueue", NULL);
        dispatch_async(mySerialDispatchQueue, ^{
        });
        dispatch_release(mySerialDispatchQueue);
        
       // 并行队列
        dispatch_queue_t myConcurrentDispatchQueue = dispatch_queue_create("com.example.gcd.MyConcurrentDispatchQueue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(myConcurrentDispatchQueue, ^{
            NSLog(@"block on myConcurrentDispatchQueue");
        });
        dispatch_release(myConcurrentDispatchQueue);
    
    • 方法二: 获取系统标准提供的 Dispatch Queue
      // 主队列   
        dispatch_queue_t mainDispatchQueue =   dispatch_get_main_queue();
        
      // 全局并发队列(4种优先级)
        dispatch_queue_t globalDispatchQueueHeigh = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
        dispatch_queue_t globalDispatchQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_queue_t globalDispatchQueueLow = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
        dispatch_queue_t globalDispatchQueueBackground = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    

    2.延时操作

    • 3s后,将block追加到主队列中进行执行;
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSLog(@"waited at least 3 seconds");
        });
    

    3.队列组

    • 在一系列操作完成之后,再执行其他内容
        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(@"blk0");
        });
        dispatch_group_async(group, queue, ^{
            NSLog(@"blk1");
        });
        dispatch_group_async(group, queue, ^{
            NSLog(@"blk2");
        });
        
        // 推荐
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"done");
        });
    
      // 不推荐
        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1);
        long result = dispatch_group_wait(group, time);
        if (result == 0) { // group 的全部处理执行结束
        }else {
        }
    //    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        
        dispatch_release(group);
    

    4.栅栏函数

    • 用于读写操作引起的相关内容;
    • 每次的执行结果可能不一样,但是写操作一定会将0,1,2,3读操作和4,5,6,7分隔开,从而达到不会误读的效果
        dispatch_queue_t myConcurrentDispatchQueue = dispatch_queue_create("com.example.gcd.MyConcurrentDispatchQueue", DISPATCH_QUEUE_CONCURRENT);
        
        __block NSInteger count = 1;
        
        void (^blk0_for_reading)(void) = ^{NSLog(@"blk0_for_reading-%li%@", count, [NSThread currentThread]);};
        void (^blk1_for_reading)(void) = ^{NSLog(@"blk1_for_reading-%li%@", count, [NSThread currentThread]);};
        void (^blk2_for_reading)(void) = ^{NSLog(@"blk2_for_reading-%li%@", count,[NSThread currentThread]);};
        void (^blk3_for_reading)(void) = ^{NSLog(@"blk3_for_reading-%li%@", count,[NSThread currentThread]);};
        
        void (^blk4_for_writing)(void) = ^{ ++count; NSLog(@"---------blk4_for_writing-%li%@", count,[NSThread currentThread]);};
        
        void (^blk5_for_reading)(void) = ^{NSLog(@"blk5_for_reading-%li%@", count,[NSThread currentThread]);};
        void (^blk6_for_reading)(void) = ^{NSLog(@"blk6_for_reading-%li%@", count,[NSThread currentThread]);};
        void (^blk7_for_reading)(void) = ^{NSLog(@"blk7_for_reading-%li%@", count,[NSThread currentThread]);};
        void (^blk8_for_reading)(void) = ^{NSLog(@"blk8_for_reading-%li%@", count,[NSThread currentThread]);};
        
        dispatch_async(myConcurrentDispatchQueue, blk0_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk1_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk2_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk3_for_reading);
        
        dispatch_barrier_async(myConcurrentDispatchQueue, blk4_for_writing);
        
        dispatch_async(myConcurrentDispatchQueue, blk5_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk6_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk7_for_reading);
        dispatch_async(myConcurrentDispatchQueue, blk8_for_reading);
    
    // 结果
    blk1_for_reading-1<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305030+0800 Test_copy_mutableCopy[1003:610433] blk0_for_reading-1<NSThread: 0x174073fc0>{number = 4, name = (null)}
    2017-10-24 12:21:57.305121+0800 Test_copy_mutableCopy[1003:610433] blk3_for_reading-1<NSThread: 0x174073fc0>{number = 4, name = (null)}
    2017-10-24 12:21:57.304973+0800 Test_copy_mutableCopy[1003:610435] blk2_for_reading-1<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305301+0800 Test_copy_mutableCopy[1003:610435] ---------blk4_for_writing-2<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305389+0800 Test_copy_mutableCopy[1003:610435] blk5_for_reading-2<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305460+0800 Test_copy_mutableCopy[1003:610435] blk6_for_reading-2<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305529+0800 Test_copy_mutableCopy[1003:610435] blk7_for_reading-2<NSThread: 0x170272e80>{number = 5, name = (null)}
    2017-10-24 12:21:57.305598+0800 Test_copy_mutableCopy[1003:610433] blk8_for_reading-2<NSThread: 0x174073fc0>{number = 4, name = (null)}
    
    

    5.死锁的产生

    必然引起死锁的两种方式

    • 主队列 + 同步函数
        NSInteger count = 3;
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_sync(mainQueue, ^{NSLog(@"mainQueue-%li%@", count,[NSThread currentThread]);});
      // result: 并没有出现结果,因为已经发生了死锁
      
    • 串行队列 + 异步函数的block内部是(该串行队列 + 同步函数)(将串行队列换成主队列依然成立)
      dispatch_queue_t serialQueue = dispatch_queue_create("com.nextapp.qiannong", NULL);
        dispatch_async(serialQueue, ^{
            dispatch_sync(serialQueue, ^{NSLog(@"no deadLock");});
        });
      // result: 并没有出现结果,因为已经发生了死锁
      

    6.dispatch_apply

    • dispatch_apply 与dispatch_sync 函数类似(dispatch_group_async, dispatch_group_notify, dispatch_group_wait),会等待处理执行结束,在向下执行;

    • dispatch_group_async 没有执行次数的要求

    • dispatch_apply 必须有执行的次数

    • dispatch_barrier_async ,用于前后都有读取异步任务,中间有一个写操作

      // 建议在dispatch_async中异步执行dispatch_apply函数
      
        dispatch_async(globalQueue, ^{
            dispatch_apply(10, globalQueue, ^(size_t index) {
                NSLog(@"%li-%@", index,[NSThread currentThread]);
            });
            dispatch_async(dispatch_get_main_queue(), ^{
                // 执行更新界面的操作
                NSLog(@"Done-%@", [NSThread currentThread]);
            });
        });
      
        // 试验之后,并没有生效
        dispatch_suspend(globalQueue); // 挂起
        dispatch_resume(globalQueue);  // 恢复
      

    7.信号量机制相关

    • 相比串行队列 和 栅栏函数 ,力度更小;
        dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        // 保证可访问NSMutableArray类对象的线程只能有1个
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        
        NSMutableArray *array = [NSMutableArray array];
        for (int idx = 0; idx < 10000; idx ++) {
            dispatch_async(globalQueue, ^{
     
               // 一直等到执行semaphore的是计数值>=1.
               //          long result = dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
              //            if (result == 0) {
              //            }else {
              //            }
                
                [array addObject:[NSNumber numberWithInt:idx]];
                
                // 执行结束之后,释放该锁, 将dsemaphore的值 + 1;
                dispatch_semaphore_signal(semaphore);
            });
        }
        
        NSLog(@"%@", array);
        dispatch_release(semaphore);
    

    8.单例

    • 在程序中,只执行一次
      // 之前的初始化操作
        static BOOL initialized = NO;
        if (initialized == NO) {
            
            /*
             * 初始化操作
             */
            
            initialized = YES;
        }
    
      // 多线程环境下更加的安全
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            /*
             * 初始化操作
             */
        });
    

    9.简记

    线程

    • dispatch_sync/async:同步/异步是否开启新线程
    • 异步不阻塞当前线程,同步阻塞当前线程
    • serial/concurrent queue:串行/并行决定开启线程的条数

    死锁

    • 同步的在当前队列中(串行)中添加任务
    • 主队列也是串行队列
    • 相互阻塞构成死锁

    信号量(semaphore)

    • 信号量是同步的(同步会阻塞当前线程)
    • semaphore.create(p): p >= 0
    • semaphore.wait(): p <= 0, 阻塞当前线程, p -= 1
    • semaphore.signal(): p += 1

    group

    • 实现多个网络的异步请求,最后再同步执行任务
    • group.enter(), group.leave(), group.notify()

    相关文章

      网友评论

          本文标题:GCD相关基础知识

          本文链接:https://www.haomeiwen.com/subject/gdptpxtx.html