美文网首页iOS 开发技巧iOS Developer
GCD 与线程的关系及常用操作

GCD 与线程的关系及常用操作

作者: TerryZhang | 来源:发表于2017-07-10 17:44 被阅读71次

dispatch queue

  • 串行队列(DISPATCH_QUEUE_CONCURRENT)

    • serial dispatch queue中的block按照先进先出(FIFO)的顺序去执行,
    • 用户可以根据需要创建任意多的serial dispatch queue
    • serial dispatch queue彼此之间是并发的
  • 并行队列(DISPATCH_QUEUE_SERIAL)

    • 一次性并发执行一个或者多个task
    • 系统提供了四个global concurrent queue,使用dispatch_get_global_queue函数就可以获取
  • Main Dispatch Queue

    • 绑定在主线程
    • FIFO
    • 全局的
  • 全局队列

    • main queue
    • 四个global concurrent queue
  • 用户创建

    • 串行
    • 并行

全局队列

main queue 的所有的操作都在主线程中进行,注意 main queue 是一个串行队列

dispatch_queue_t dispatch_get_main_queue(void)

返回全局共有的 并行队列, 主要有四个优先级

  • DISPATCH_QUEUE_PRIORITY_HIGH: QOS_CLASS_USER_INITIATED
  • DISPATCH_QUEUE_PRIORITY_DEFAULT: QOS_CLASS_DEFAULT
  • DISPATCH_QUEUE_PRIORITY_LOW: QOS_CLASS_UTILITY
  • DISPATCH_QUEUE_PRIORITY_BACKGROUND: QOS_CLASS_BACKGROUND
dispatch_queue_t dispatch_get_global_queue(long identifier, unsigned long flags);

用户自己创建

用户可以通过设置 attr 参数,创建出 串行 或 并行的队列

dispatch_queue_t dispatch_queue_create(const char *_Nullable label,
        dispatch_queue_attr_t _Nullable attr);

dispatch_get_current_queue

不要用!

dispatch queue 和 线程的关系

除了 main queue 在主线程,其他没啥关系~

- (void)mainQueueAndThread
{
    NSLog(@"thread out queue: %@", [NSThread currentThread]);

    dispatch_queue_t main_queue = dispatch_get_main_queue();

    for (NSInteger i = 0; i< 100; i++) {

//        /**
//         *  !!!特别注意,这里会形成死锁
//         */
//        dispatch_sync(main_queue, ^{
//            NSLog(@"thread in main queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
//        });

        /**
         *  通过 Log 发现,所有的任务都执行在主线程上
         */
        dispatch_async(main_queue, ^{
            NSLog(@"dispatch_async in main queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
        });
    }
}

- (void)serialQueueAndThread
{
    NSLog(@"thread out queue: %@", [NSThread currentThread]);

    dispatch_queue_t serial_queue = dispatch_queue_create("me.terry.MySerialQueue", DISPATCH_QUEUE_SERIAL);

    for (NSInteger i = 0; i< 100; i++) {
        dispatch_sync(serial_queue, ^{
            NSLog(@"dispatch_sync in serial queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
        });

        /**
         *  通过 Log 发现:
         *  1. 虽然是串行队列, 但是没有对应的串行线程,任务执行在不同的线程上
         *  2. 虽然使用异步派发,但是仍然遵循 FIFO
         *  3. 虽然指定了队列,但是执行同步操作的时候,仍然执行在主线程上
         */
        dispatch_async(serial_queue, ^{
            NSLog(@"dispatch_async in serial queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
        });
    }
}

- (void)concurrentQueueAndThread
{
    NSLog(@"thread out queue: %@", [NSThread currentThread]);

    dispatch_queue_t concurrent_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

    for (NSInteger i = 0; i< 100; i++) {
        /**
         *  通过的 Log 发现:
         *  1. 虽然指定了并行队列,但是执行同步操作的时候,仍然执行在主线程上
         *  2. 并行队列 和 上述的 serial_queue 有一些线程是相同的,所以队列和线程是没有对应关系的
         *  3. 异步派发,并发执行task,不遵循 FIFO了
         */
        dispatch_sync(concurrent_queue, ^{
            NSLog(@"dispatch_sync in concurrent queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
        });
        dispatch_async(concurrent_queue, ^{
            NSLog(@"dispatch_async in concurrent queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
        });
    }
}

- (void)dispatchSyncAndThread
{
    NSLog(@"main thread: %@", [NSThread mainThread]);

    NSThread *testThread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"thread out queue: %@", [NSThread currentThread]);

        dispatch_queue_t main_queue = dispatch_get_main_queue();
        dispatch_queue_t serial_queue = dispatch_queue_create("me.terry.MySerialQueue", DISPATCH_QUEUE_SERIAL);
        dispatch_queue_t concurrent_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

        for (NSInteger i = 0; i< 100; i++) {
            /**
             *  执行在主线程
             */
            dispatch_sync(main_queue, ^{
                NSLog(@"dispatch_sync in main queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
            });
        }
        for (NSInteger i = 0; i< 100; i++) {
            /**
             *  执行在上下文线程
             */
            dispatch_sync(serial_queue, ^{
                NSLog(@"dispatch_sync in serial queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
            });
        }
        for (NSInteger i = 0; i< 100; i++) {
            /**
             *  执行在上下文线程
             */
            dispatch_sync(concurrent_queue, ^{
                NSLog(@"dispatch_sync in concurrent queue ,i:%@, thread:%@", @(i), [NSThread currentThread]);
            });
        }

    }];
    [testThread start];
}

队列的操作

同步操作

void dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);

dispatch_sync 会阻塞线程,不论指定同步队列还是异步队列,都会等待1执行完,才会执行2

dispatch_sync(queue, ^{
    sleep(3);
    // do something 1
});

// do something 2

异步操作

void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

- (void)dispatchAsyncDemo
{
    dispatch_queue_t serial_queue = dispatch_queue_create("me.terry.MySerialQueue", DISPATCH_QUEUE_SERIAL);

    /**
     *  不论指定是串行队列还是并行队列,不会 block , 顺序 3 1 2
     */
    dispatch_async(serial_queue, ^{
        NSLog(@"%@",@"in async block 111");
        sleep(3);
        NSLog(@"%@",@"in async block 222");
    });
    NSLog(@"%@",@"in sync block 333");
}

dispatch_once

- (void)dispatchOnceDemo
{
    NSLog(@"这个 Log 每次都会出现");
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"这个 Log 只会出一次");
    });
}

dispatch_group

- (void)dispatchGroupDemo
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    for (NSInteger i = 0; i < 10000; i++) {
        dispatch_group_async(dispatchGroup, queue, ^{
            NSLog(@"dispatch Group Async Demo index:%@",@(i));
        });
    }

    // 非阻塞
    dispatch_queue_t notifyQueue = dispatch_get_main_queue();
    dispatch_group_notify(dispatchGroup, notifyQueue, ^{
        // Continue processing after completing tasks
        NSLog(@"Dispatch Group Done with notification");
    });
    NSLog(@"dispatch_group_notify will not block the thread");

    // 阻塞当前线程
    dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER);
    // Continue processing after completing tasks
    NSLog(@"Dispatch Group Done after blocking thread");
}

dispatch_apply

- (void)dispatchApplyDemo
{
    /**
     *  dispatch apply 可以实现类似 dispatch group 的功能, 注意防止同步造成的死锁问题
     */
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_apply(1000, queue, ^(size_t i) {
        NSLog(@"dispatch Apply Demo index:%@",@(i));
    });
    NSLog(@"Dispatch Apply Demo Done after blocking thread");
}

dispatch_barrier

- (void)dispatchBarrierDemo
{
    __block NSInteger someValue = 0;

    someValue = 0;

    void(^readValueBlock)(void) = ^() {
        NSLog(@"some value:%@", @(someValue));
    };

    void(^writeValueBlock)(void) = ^() {
        someValue ++;
    };

    /**
     *  这里注意 dispatch_barrier_async 只能在 使用 dispatch_queue_create 创建的 队列中使用
     *  如果在 globe queue 中使用,与 dispatch_async 没有区别
     *  https://stackoverflow.com/questions/10808476/how-should-i-use-gcd-dispatch-barrier-async-in-ios-seems-to-execute-before-and
     */
    dispatch_queue_t queue = dispatch_queue_create("12312312", DISPATCH_QUEUE_CONCURRENT);

    /**
     *  串行队列可以很好的防止数据竞争的问题, 但是并发队列有可能会有更好的性能
     *  但是由于并发队列任务的执行顺序不能确定,可能发生数据竞争,导致最终结果不正确
     */
    for (NSInteger i = 0; i < 1000; i++) {
        dispatch_async(queue, readValueBlock);
    }
    for (NSInteger i = 0; i < 1000; i++) {
        dispatch_async(queue, writeValueBlock);
    }
    for (NSInteger i = 0; i < 1000; i++) {
        dispatch_async(queue, readValueBlock);
    }

    dispatch_barrier_sync(queue, ^{
        someValue = 0;
        NSLog(@"----------------------");
    });

    /**
     *  使用dispatch_barrier_async 可以保证写操作执行时,不会发生数据竞争,保证最终结果正确
     *  但是好像没有啥效果
     */
    for (NSInteger i = 0; i < 1000; i++) {
        dispatch_async(queue, readValueBlock);
    }
    for (NSInteger i = 0; i < 1000; i++) {
        /**
         *  dispatch_barrier_async 中文叫栅栏函数,它等待所有位于barrier函数之前的操作执行完毕后执行,并且在barrier函数执行之后,barrier函数之后的操作才会得到执行
         */
        dispatch_barrier_async(queue, writeValueBlock);
    }
    for (NSInteger i = 0; i < 1000; i++) {
        dispatch_async(queue, readValueBlock);
    }
}

dadas

- (void)dispatchSuspendAndResumeDemo
{
    void(^taskBlock)(void) = ^() {
        NSLog(@"task start");
        sleep(2);
        NSLog(@"task stop");
    };

    dispatch_queue_t queue = dispatch_queue_create("12312312", DISPATCH_QUEUE_SERIAL);

    for (NSInteger i = 0; i < 10; i++) {
        dispatch_async(queue, taskBlock);
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /**
         *  挂起的队列,已经执行的任务仍然会继续执行,但是队列中其他没有执行的任务不会执行
         */
        dispatch_suspend(queue);
        NSLog(@"dispatch_suspend");
    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /**
         *  队列恢复以后,其他的任务继续执行
         */
        dispatch_resume(queue);
        NSLog(@"dispatch_resume");
    });
}

dispatch_semephore

- (void)dispatchSemaphoreDemo
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // 不考虑顺序,向NSMutableArray 添加元素
    /*
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < 10000; i++) {
        dispatch_async(queue, ^{
            [array addObject:@(i)]; // 异常结束
        });
    }
     */

    /**
     *  生成信号量,
     *  初始值为1 -》可访问 NSMutableArray 类对象的线程同时 只有 1 个
     */
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    NSMutableArray *array = [NSMutableArray array];

    for (NSInteger i = 0; i < 10000; i++) {
        dispatch_async(queue, ^{
            /**
             *  计数器为 0 的时候等待,直到大于等于 1
             */
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            /**
             *  执行到此时,计数器减 1
             *  由于只有1, 所以此时 计数器为0,其他线程不会通过,保证只有一个线程
             */
            [array addObject:@(i)];
            /**
             *  计数器+1,
             *  注意:如果系统销毁时,semaphore的技术比初始值小,会认为处于 in use 的状态,会 crash
             */
            dispatch_semaphore_signal(semaphore);
        });
    }
}

相关文章

  • GCD 与线程的关系及常用操作

    dispatch queue 串行队列(DISPATCH_QUEUE_CONCURRENT)serial disp...

  • GCD

    GCD 队列与线程的关系 主队列和主线程 『ios』主线程 和 主队列的关系,绝对安全的UI操作,主线程中一定是主...

  • iOS 多线程知识点总结

    1. 日常开发中常用的多线程方式? GCD; 简单的线程同步, 子线程操作; NSOperation AFNetw...

  • GCD几种组合的使用

    ### GCD常用队列 主线程:UI操作在这条线程上而已,这是主线程和其它线程的区别.主线程 挂掉不会影响其它线程...

  • 7.3 多线程-GCD

    多线程-GCD 多线程-GCD-串行并行 多线程-GCD.png GCD-线程的通讯、延时操作、定时器 GCD-线...

  • ios面试题

    runtime介绍 runLoop与多线程关系 多线程原理(GCD、NSOperation) AFNetworki...

  • ReactiveCocoa 直接回主线程

    我们经常用GCD来在'subscribeNext'中切到主线程去操作UI比如: 其实RACSignal 'del...

  • 十一、ios线程调用学习

    常用线程方式:GCD 一、GCD学习 Grand Central Dispatch(GCD) 是 Apple 开发...

  • iOS --- 多线程之NSOperation

    NSOperation基于GCD封装实现的,比GCD稍慢,可设定各个操作之间的依赖关系及优先级等。相对于GCD而言...

  • iOS多线程开发—GCD(二)

    前言 在上一篇文章iOS多线程开发—GCD(二)中我介绍了什么是多线程,GCD与线程的关系,以及如何创建队列和简单...

网友评论

    本文标题:GCD 与线程的关系及常用操作

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