GCD的dispatch_get_specific与dispatch_queue_set_specific

6,375 阅读5分钟

概述

GCD是一个多核编程的解决方案。它主要用于优化应用程序以支持多核处理器。

GCD介绍

要理解GCD的使用就必须先知道GCD中的任务和队列的概念:

  • 任务 任务即执行操作的意思,换句话说就是你在线程中执行的那段代码。在 GCD 中是放在 block 中的。执行任务有两种方式:『同步执行』 和 『异步执行』。两者的主要区别是:是否等待队列的任务执行结束,以及是否具备开启新线程的能力。

  • 队列(Dispatch Queue): 队列指执行任务的队列。队列是一种特殊的线性表,采用 FIFO(先进先出)的原则,即新任务总是被插入到队列的末尾,而读取任务的时候总是从队列的头部开始读取。每执行一个任务,则从队列中释放一个任务。队列的结构可参考下图:

image.png

这时候来谈GCD的使用就很简单了,只有两步:

  1. 创建一个队列(串行队列或并发队列);

  2. 将任务追加到队列中,然后系统就会根据队列类型和任务执行方式执行任务(同步执行或异步执行)。

dispatch_get_specific与dispatch_queue_set_specific

  • dispatch_queue_set_specific是向队列设置一个标识,如:
//向queue1设置一个queueKey1标识
dispatch_queue_set_specific(queue1, queueKey1, &queueKey1,NULL);
  • dispatch_get_specific是在当前队列中取出标识,用来判断是否当前队列是标识所在的队列;

注意iOS中线程和队列的关系,所有的动作都是在队列中执行的!

一个简单的例子:

-(void)testGCD {
    static void *queueKey1 = "queueKey1";
    dispatch_queue_t queue1 = dispatch_queue_create(queueKey1, DISPATCH_QUEUE_SERIAL);

    dispatch_queue_set_specific(queue1, queueKey1, &queueKey1, NULL);
    NSLog(@"1. 当前线程是: %@, ",[NSThread currentThread]);

    if (dispatch_get_specific(queueKey1)) {

        //因为当前队列是主队列,不是queue1队列,所以取不到queueKey1对应的值,故而不执行
        NSLog(@"2. 当前线程是: %@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:1];

    }else{
        NSLog(@"3. 当前线程是: %@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:1];
    }
    
    dispatch_sync(queue1, ^{

        NSLog(@"4. 当前线程是: %@",[NSThread currentThread]);

        if (dispatch_get_specific(queueKey1)) {
             //当前队列是queue1队列,所以能取到queueKey1对应的值,故而执行
            NSLog(@"5. 当前线程是: %@",[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }else{
            NSLog(@"6. 当前线程是: %@",[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }

    });

    dispatch_async(queue1, ^{

        NSLog(@"7. t当前线程是: %@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:1];
        
        if (dispatch_get_specific(queueKey1)) {

             //当前队列是queue1队列,所以能取到queueKey1对应的值,故而执行
            NSLog(@"8. 当前线程是: %@",[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }else{

            NSLog(@"9. 当前线程是: %@",[NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        }
    });
}

//输出:
2022-05-25 10:51:56.460219+0800 demo[14026:3587457] 1. 当前线程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}, 
2022-05-25 10:51:56.460346+0800 demo[14026:3587457] 3. 当前线程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:57.461678+0800 demo[14026:3587457] 4. 当前线程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:57.461955+0800 demo[14026:3587457] 5. 当前线程是: <_NSMainThread: 0x283a648c0>{number = 1, name = main}
2022-05-25 10:51:58.463502+0800 demo[14026:3587541] 7. t当前线程是: <NSThread: 0x283a53840>{number = 3, name = (null)}
2022-05-25 10:51:59.468791+0800 demo[14026:3587541] 8. 当前线程是: <NSThread: 0x283a53840>{number = 3, name = (null)}

这里解释一下4的当前线程为什么是主线程,因为串行队列加同步执行不会产生新线程,直接沿用当前线程也就是主线程。只有串行队列加异步执行才会产生新线程,7就证明了这一点。

常见的应用场景

判断是否在主队列运行

在 iOS 中,如果我们要判断代码是否运行在主线程,可以直接使用NSThread.isMainThread()方法。但如果要判断是否运行在主队列(main queue)呢?

需要注意的是,每个应用都只有一个主线程,但主线程中可能有多个队列,不仅仅只有主队列,所以 NSThread.isMainThread() 方法并没有办法判断是否是在主队列运行。而GCD也没有提供相应的方法。那该如何处理呢?

来看看 React Native 的处理方式:

 BOOL RCTIsMainQueue()
{
  static void *mainQueueKey = &mainQueueKey;

  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{

    dispatch_queue_set_specific(dispatch_get_main_queue(),

                                mainQueueKey, mainQueueKey, NULL);

  });

  return dispatch_get_specific(mainQueueKey) == mainQueueKey;

}

可以看到这里使用了 dispatch_queue_set_specific 和 dispatch_get_specific 。实际上是通过 dispatch_queue_set_specific 方法给主队列(main queue)关联了一个 key-value 对,再通过 dispatch_get_specific 从当前队列中取出 mainQueueKey 对应的 value。如果是主队列,取出来的值就是写入的值,如果是其它主队列,取出的值就是另一个值或者是 NULL。

当然,同样可以用类似的方式来设置其它的队列(注意设置全局并发队列无效)。

串行执行即统一在某个队列执行

 - (id)init {

    self = [super init];

    _protocolQueue = dispatch_queue_create("protocol.process.queue", NULL);

    dispatch_queue_set_specific(_protocolQueue, _protocolQueueKey, (__bridge void *)self, NULL);

    return self;

}

BOOL RCTIsMainQueue()

{

  static void *mainQueueKey = &mainQueueKey;

  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{

    dispatch_queue_set_specific(dispatch_get_main_queue(),

                                mainQueueKey, mainQueueKey, NULL);

  });

  return dispatch_get_specific(mainQueueKey) == mainQueueKey;

}


void runOnMainQueueWithoutDeadlocking(void (^block)(void)) {

    if ([self RCTIsMainQueue]) {

        block();

    } else {

        dispatch_sync(dispatch_get_main_queue(), block);

    }

}

void runSynchronouslyOnProtocolProcessingQueue(void (^block)(void)) {

    dispatch_queue_t processQueue = [[XXXConfig sharedInstance] protocolQueue];

    if (dispatch_get_specific([[XXXConfig sharedInstance] protocolQueueKey])){

        block();

    } else {

        dispatch_sync(processQueue, block);

    }

}

防止死锁

看看FMDB如何使用dispatch_queue_set_specific和dispatch_get_specific来防止死锁的

static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;

//创建串行队列,所有数据库的操作都在这个队列里
_queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);

//标记队列
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);

//检查是否是同一个队列来避免死锁的方法
- (void)inDatabase:(void (^)(FMDatabase *db))block {

    FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);

    assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");

}