Parser 中GCD的使用(1)

2020-01-17  本文已影响0人  老猫_2017

PFThreadsafety 线程安全,用来

  1. 创建 串行队列,设定specific 名称,用来比对 是否是同一queue
static void *const PFThreadsafetyQueueIDKey = (void *)&PFThreadsafetyQueueIDKey;

dispatch_queue_t PFThreadsafetyCreateQueueForObject(id object) {
    NSString *label = [NSStringFromClass([object class]) stringByAppendingString:@".synchronizationQueue"];
    dispatch_queue_t queue = dispatch_queue_create(label.UTF8String, DISPATCH_QUEUE_SERIAL);

    void *uuid = calloc(1, sizeof(uuid));
    dispatch_queue_set_specific(queue, PFThreadsafetyQueueIDKey, uuid, free);

    return queue;
}
  1. 保证在相同的queue,执行 block, 比对specific value
void PFThreadsafetySafeDispatchSync(dispatch_queue_t queue, dispatch_block_t block) {
    void *uuidMine = dispatch_get_specific(PFThreadsafetyQueueIDKey);
    void *uuidOther = dispatch_queue_get_specific(queue, PFThreadsafetyQueueIDKey);

    if (uuidMine == uuidOther) {
        block();
    } else {
        dispatch_sync(queue, block);
    }
}

上一篇下一篇

猜你喜欢

热点阅读