PINOperationQueue.m 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // PINOperationQueue.m
  3. // Pods
  4. //
  5. // Created by Garrett Moon on 8/23/16.
  6. //
  7. //
  8. #import "PINOperationQueue.h"
  9. #import <pthread.h>
  10. @class PINOperation;
  11. @interface NSNumber (PINOperationQueue) <PINOperationReference>
  12. @end
  13. @interface PINOperationQueue () {
  14. pthread_mutex_t _lock;
  15. //increments with every operation to allow cancelation
  16. NSUInteger _operationReferenceCount;
  17. dispatch_group_t _group;
  18. dispatch_queue_t _serialQueue;
  19. BOOL _serialQueueBusy;
  20. dispatch_semaphore_t _concurrentSemaphore;
  21. dispatch_queue_t _concurrentQueue;
  22. dispatch_queue_t _semaphoreQueue;
  23. NSMutableOrderedSet<PINOperation *> *_queuedOperations;
  24. NSMutableOrderedSet<PINOperation *> *_lowPriorityOperations;
  25. NSMutableOrderedSet<PINOperation *> *_defaultPriorityOperations;
  26. NSMutableOrderedSet<PINOperation *> *_highPriorityOperations;
  27. NSMapTable<id<PINOperationReference>, PINOperation *> *_referenceToOperations;
  28. }
  29. @end
  30. @interface PINOperation : NSObject
  31. @property (nonatomic, strong) dispatch_block_t block;
  32. @property (nonatomic, strong) id <PINOperationReference> reference;
  33. @property (nonatomic, assign) PINOperationQueuePriority priority;
  34. + (instancetype)operationWithBlock:(dispatch_block_t)block reference:(id <PINOperationReference>)reference priority:(PINOperationQueuePriority)priority;
  35. @end
  36. @implementation PINOperation
  37. + (instancetype)operationWithBlock:(dispatch_block_t)block reference:(id<PINOperationReference>)reference priority:(PINOperationQueuePriority)priority
  38. {
  39. PINOperation *operation = [[self alloc] init];
  40. operation.block = block;
  41. operation.reference = reference;
  42. operation.priority = priority;
  43. return operation;
  44. }
  45. @end
  46. @implementation PINOperationQueue
  47. - (instancetype)initWithMaxConcurrentOperations:(NSUInteger)maxConcurrentOperations
  48. {
  49. return [self initWithMaxConcurrentOperations:maxConcurrentOperations concurrentQueue:dispatch_queue_create("PINOperationQueue Concurrent Queue", DISPATCH_QUEUE_CONCURRENT)];
  50. }
  51. - (instancetype)initWithMaxConcurrentOperations:(NSUInteger)maxConcurrentOperations concurrentQueue:(dispatch_queue_t)concurrentQueue
  52. {
  53. if (self = [super init]) {
  54. NSAssert(maxConcurrentOperations > 1, @"Max concurrent operations must be greater than 1. If it's one, just use a serial queue!");
  55. _operationReferenceCount = 0;
  56. pthread_mutexattr_t attr;
  57. pthread_mutexattr_init(&attr);
  58. //mutex must be recursive to allow scheduling of operations from within operations
  59. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  60. pthread_mutex_init(&_lock, &attr);
  61. _group = dispatch_group_create();
  62. _serialQueue = dispatch_queue_create("PINOperationQueue Serial Queue", DISPATCH_QUEUE_SERIAL);
  63. _concurrentQueue = concurrentQueue;
  64. //Create a queue with max - 1 because this plus the serial queue add up to max.
  65. _concurrentSemaphore = dispatch_semaphore_create(maxConcurrentOperations - 1);
  66. _semaphoreQueue = dispatch_queue_create("PINOperationQueue Serial Semaphore Queue", DISPATCH_QUEUE_SERIAL);
  67. _queuedOperations = [[NSMutableOrderedSet alloc] init];
  68. _lowPriorityOperations = [[NSMutableOrderedSet alloc] init];
  69. _defaultPriorityOperations = [[NSMutableOrderedSet alloc] init];
  70. _highPriorityOperations = [[NSMutableOrderedSet alloc] init];
  71. _referenceToOperations = [NSMapTable weakToWeakObjectsMapTable];
  72. }
  73. return self;
  74. }
  75. - (void)dealloc
  76. {
  77. pthread_mutex_destroy(&_lock);
  78. }
  79. + (instancetype)sharedOperationQueue
  80. {
  81. static PINOperationQueue *sharedOperationQueue = nil;
  82. static dispatch_once_t onceToken;
  83. dispatch_once(&onceToken, ^{
  84. sharedOperationQueue = [[PINOperationQueue alloc] initWithMaxConcurrentOperations:MAX([[NSProcessInfo processInfo] activeProcessorCount], 2)];
  85. });
  86. return sharedOperationQueue;
  87. }
  88. - (id <PINOperationReference>)nextOperationReference
  89. {
  90. [self lock];
  91. id <PINOperationReference> reference = [NSNumber numberWithUnsignedInteger:++_operationReferenceCount];
  92. [self unlock];
  93. return reference;
  94. }
  95. - (id <PINOperationReference>)addOperation:(dispatch_block_t)block
  96. {
  97. return [self addOperation:block withPriority:PINOperationQueuePriorityDefault];
  98. }
  99. - (id <PINOperationReference>)addOperation:(dispatch_block_t)block withPriority:(PINOperationQueuePriority)priority
  100. {
  101. id <PINOperationReference> reference = [self nextOperationReference];
  102. NSMutableOrderedSet *queue = [self operationQueueWithPriority:priority];
  103. PINOperation *operation = [PINOperation operationWithBlock:block reference:reference priority:priority];
  104. [self lock];
  105. dispatch_group_enter(_group);
  106. [queue addObject:operation];
  107. [_queuedOperations addObject:operation];
  108. [_referenceToOperations setObject:operation forKey:reference];
  109. [self unlock];
  110. [self scheduleNextOperations:NO];
  111. return reference;
  112. }
  113. - (void)cancelAllOperations
  114. {
  115. [self lock];
  116. for (PINOperation *operation in [[_referenceToOperations copy] objectEnumerator]) {
  117. [self locked_cancelOperation:operation.reference];
  118. }
  119. [self unlock];
  120. }
  121. - (BOOL)cancelOperation:(id <PINOperationReference>)operationReference
  122. {
  123. [self lock];
  124. BOOL success = [self locked_cancelOperation:operationReference];
  125. [self unlock];
  126. return success;
  127. }
  128. - (BOOL)locked_cancelOperation:(id <PINOperationReference>)operationReference
  129. {
  130. BOOL success = NO;
  131. PINOperation *operation = [_referenceToOperations objectForKey:operationReference];
  132. if (operation) {
  133. NSMutableOrderedSet *queue = [self operationQueueWithPriority:operation.priority];
  134. if ([queue containsObject:operation]) {
  135. success = YES;
  136. [queue removeObject:operation];
  137. [_queuedOperations removeObject:operation];
  138. dispatch_group_leave(_group);
  139. }
  140. }
  141. return success;
  142. }
  143. - (void)setOperationPriority:(PINOperationQueuePriority)priority withReference:(id <PINOperationReference>)operationReference
  144. {
  145. [self lock];
  146. PINOperation *operation = [_referenceToOperations objectForKey:operationReference];
  147. if (operation && operation.priority != priority) {
  148. NSMutableOrderedSet *oldQueue = [self operationQueueWithPriority:operation.priority];
  149. [oldQueue removeObject:operation];
  150. operation.priority = priority;
  151. NSMutableOrderedSet *queue = [self operationQueueWithPriority:priority];
  152. [queue addObject:operation];
  153. }
  154. [self unlock];
  155. }
  156. /**
  157. Schedule next operations schedules the next operation by queue order onto the serial queue if
  158. it's available and one operation by priority order onto the concurrent queue.
  159. */
  160. - (void)scheduleNextOperations:(BOOL)onlyCheckSerial
  161. {
  162. [self lock];
  163. //get next available operation in order, ignoring priority and run it on the serial queue
  164. if (_serialQueueBusy == NO) {
  165. PINOperation *operation = [self locked_nextOperationByQueue];
  166. if (operation) {
  167. _serialQueueBusy = YES;
  168. dispatch_async(_serialQueue, ^{
  169. operation.block();
  170. dispatch_group_leave(_group);
  171. [self lock];
  172. _serialQueueBusy = NO;
  173. [self unlock];
  174. //see if there are any other operations
  175. [self scheduleNextOperations:YES];
  176. });
  177. }
  178. }
  179. [self unlock];
  180. if (onlyCheckSerial) {
  181. return;
  182. }
  183. dispatch_async(_semaphoreQueue, ^{
  184. dispatch_semaphore_wait(_concurrentSemaphore, DISPATCH_TIME_FOREVER);
  185. [self lock];
  186. PINOperation *operation = [self locked_nextOperationByPriority];
  187. [self unlock];
  188. if (operation) {
  189. dispatch_async(_concurrentQueue, ^{
  190. operation.block();
  191. dispatch_group_leave(_group);
  192. dispatch_semaphore_signal(_concurrentSemaphore);
  193. });
  194. } else {
  195. dispatch_semaphore_signal(_concurrentSemaphore);
  196. }
  197. });
  198. }
  199. - (NSMutableOrderedSet *)operationQueueWithPriority:(PINOperationQueuePriority)priority
  200. {
  201. switch (priority) {
  202. case PINOperationQueuePriorityLow:
  203. return _lowPriorityOperations;
  204. case PINOperationQueuePriorityDefault:
  205. return _defaultPriorityOperations;
  206. case PINOperationQueuePriorityHigh:
  207. return _highPriorityOperations;
  208. default:
  209. NSAssert(NO, @"Invalid priority set");
  210. return _defaultPriorityOperations;
  211. }
  212. }
  213. //Call with lock held
  214. - (PINOperation *)locked_nextOperationByPriority
  215. {
  216. PINOperation *operation = [_highPriorityOperations firstObject];
  217. if (operation == nil) {
  218. operation = [_defaultPriorityOperations firstObject];
  219. }
  220. if (operation == nil) {
  221. operation = [_lowPriorityOperations firstObject];
  222. }
  223. if (operation) {
  224. [self locked_removeOperation:operation];
  225. }
  226. return operation;
  227. }
  228. //Call with lock held
  229. - (PINOperation *)locked_nextOperationByQueue
  230. {
  231. PINOperation *operation = [_queuedOperations firstObject];
  232. [self locked_removeOperation:operation];
  233. return operation;
  234. }
  235. - (void)waitUntilAllOperationsAreFinished
  236. {
  237. [self scheduleNextOperations:NO];
  238. dispatch_group_wait(_group, DISPATCH_TIME_FOREVER);
  239. }
  240. //Call with lock held
  241. - (void)locked_removeOperation:(PINOperation *)operation
  242. {
  243. if (operation) {
  244. NSMutableOrderedSet *priorityQueue = [self operationQueueWithPriority:operation.priority];
  245. [priorityQueue removeObject:operation];
  246. [_queuedOperations removeObject:operation];
  247. }
  248. }
  249. - (void)lock
  250. {
  251. pthread_mutex_lock(&_lock);
  252. }
  253. - (void)unlock
  254. {
  255. pthread_mutex_unlock(&_lock);
  256. }
  257. @end