PFThreadsafety
线程安全,用来
-
创建 串行队列,设定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;
}
-
保证在相同的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);
}
}
网友评论