1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| #import "JPThreadsafety.h"
static void *const JPThreadsafetyQueueIDKey = (void *)&JPThreadsafetyQueueIDKey;
dispatch_queue_t JPThreadsafetyCreateQueueForObject(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, JPThreadsafetyQueueIDKey, uuid, free);
return queue;
}
void JPThreadsafetySafeDispatchSync(dispatch_queue_t queue, dispatch_block_t block) {
void* uuidMine = dispatch_get_specific(JPThreadsafetyQueueIDKey);
void* uuidOther = dispatch_queue_get_specific(queue, JPThreadsafetyQueueIDKey);
if (uuidMine == uuidOther) {
block();
} else {
dispatch_sync(queue, block);
}
}
|