美文网首页
Parser 中GCD的使用(1)

Parser 中GCD的使用(1)

作者: 老猫_2017 | 来源:发表于2020-01-17 10:54 被阅读0次

    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);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Parser 中GCD的使用(1)

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