|
12 | 12 | @interface SDCallbackQueue () |
13 | 13 |
|
14 | 14 | @property (nonatomic, strong, nonnull) dispatch_queue_t queue; |
| 15 | +@property (nonatomic, strong, nonnull) NSThread *thread; |
15 | 16 |
|
16 | 17 | @end |
17 | 18 |
|
@@ -20,8 +21,28 @@ static void SDReleaseBlock(void *context) { |
20 | 21 | CFRelease(context); |
21 | 22 | } |
22 | 23 |
|
| 24 | +static void SDSafeMainAsync(SDCallbackQueue *callbackQueue, dispatch_block_t _Nonnull block) { |
| 25 | + // Extend gcd queue's life cycle |
| 26 | + dispatch_queue_t queue = callbackQueue.queue; |
| 27 | + if (NSThread.isMainThread) { |
| 28 | + // Check 1, for cases when global queue call `dispatch_sync` on main thread. |
| 29 | + const char *currentLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL); |
| 30 | + const char *mainLabel = dispatch_queue_get_label(dispatch_get_main_queue()); |
| 31 | + if (mainLabel == currentLabel) { |
| 32 | + block(); |
| 33 | + return; |
| 34 | + } |
| 35 | + // Check 2, since main queue can never execute on non-main thread. |
| 36 | + if (queue == dispatch_get_main_queue()) { |
| 37 | + block(); |
| 38 | + return; |
| 39 | + } |
| 40 | + } |
| 41 | + dispatch_async(dispatch_get_main_queue(), block); |
| 42 | +} |
| 43 | + |
23 | 44 | static void SDSafeExecute(SDCallbackQueue *callbackQueue, dispatch_block_t _Nonnull block, BOOL async) { |
24 | | - // Extendc gcd queue's life cycle |
| 45 | + // Extend gcd queue's life cycle |
25 | 46 | dispatch_queue_t queue = callbackQueue.queue; |
26 | 47 | // Special handle for main queue label only (custom queue can have the same label) |
27 | 48 | const char *label = dispatch_queue_get_label(queue); |
@@ -57,6 +78,9 @@ - (instancetype)initWithDispatchQueue:(dispatch_queue_t)queue { |
57 | 78 | CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault); |
58 | 79 | dispatch_queue_set_specific(queue, SDCallbackQueueKey, (void *)UUID, SDReleaseBlock); |
59 | 80 | _queue = queue; |
| 81 | + _policy = SDCallbackPolicyMainAsyncSafe; |
| 82 | + // global queue can execute on main thread, like call `dispatch_sync(globalQueue)` in main thread |
| 83 | + _thread = NSThread.currentThread; |
60 | 84 | } |
61 | 85 | return self; |
62 | 86 | } |
@@ -94,6 +118,9 @@ - (void)sync:(nonnull dispatch_block_t)block { |
94 | 118 | case SDCallbackPolicyInvoke: |
95 | 119 | block(); |
96 | 120 | break; |
| 121 | + case SDCallbackPolicyMainAsyncSafe: |
| 122 | + SDSafeMainAsync(self, block); |
| 123 | + break; |
97 | 124 | default: |
98 | 125 | SDSafeExecute(self, block, NO); |
99 | 126 | break; |
@@ -111,6 +138,9 @@ - (void)async:(nonnull dispatch_block_t)block { |
111 | 138 | case SDCallbackPolicyInvoke: |
112 | 139 | block(); |
113 | 140 | break; |
| 141 | + case SDCallbackPolicyMainAsyncSafe: |
| 142 | + SDSafeMainAsync(self, block); |
| 143 | + break; |
114 | 144 | default: |
115 | 145 | SDSafeExecute(self, block, YES); |
116 | 146 | break; |
|