forked from pinterest/PINOperation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPINOperationQueue.m
471 lines (390 loc) · 14.6 KB
/
PINOperationQueue.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//
// PINOperationQueue.m
// Pods
//
// Created by Garrett Moon on 8/23/16.
//
//
#import "PINOperationQueue.h"
#import <pthread.h>
@class PINOperation;
@interface NSNumber (PINOperationQueue) <PINOperationReference>
@end
@interface PINOperationQueue () {
pthread_mutex_t _lock;
//increments with every operation to allow cancelation
NSUInteger _operationReferenceCount;
NSUInteger _maxConcurrentOperations;
dispatch_group_t _group;
dispatch_queue_t _serialQueue;
BOOL _serialQueueBusy;
dispatch_semaphore_t _concurrentSemaphore;
dispatch_queue_t _concurrentQueue;
dispatch_queue_t _semaphoreQueue;
NSMutableOrderedSet<PINOperation *> *_queuedOperations;
NSMutableOrderedSet<PINOperation *> *_lowPriorityOperations;
NSMutableOrderedSet<PINOperation *> *_defaultPriorityOperations;
NSMutableOrderedSet<PINOperation *> *_highPriorityOperations;
NSMapTable<id<PINOperationReference>, PINOperation *> *_referenceToOperations;
NSMapTable<NSString *, PINOperation *> *_identifierToOperations;
}
@end
@interface PINOperation : NSObject
@property (nonatomic, strong) PINOperationBlock block;
@property (nonatomic, strong) id <PINOperationReference> reference;
@property (nonatomic, assign) PINOperationQueuePriority priority;
@property (nonatomic, strong) NSMutableArray<dispatch_block_t> *completions;
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) id data;
+ (instancetype)operationWithBlock:(PINOperationBlock)block reference:(id <PINOperationReference>)reference priority:(PINOperationQueuePriority)priority identifier:(nullable NSString *)identifier data:(nullable id)data completion:(nullable dispatch_block_t)completion;
- (void)addCompletion:(nullable dispatch_block_t)completion;
@end
@implementation PINOperation
+ (instancetype)operationWithBlock:(PINOperationBlock)block reference:(id<PINOperationReference>)reference priority:(PINOperationQueuePriority)priority identifier:(NSString *)identifier data:(id)data completion:(dispatch_block_t)completion
{
PINOperation *operation = [[self alloc] init];
operation.block = block;
operation.reference = reference;
operation.priority = priority;
operation.identifier = identifier;
operation.data = data;
[operation addCompletion:completion];
return operation;
}
- (void)addCompletion:(dispatch_block_t)completion
{
if (completion == nil) {
return;
}
if (_completions == nil) {
_completions = [NSMutableArray array];
}
[_completions addObject:completion];
}
@end
@implementation PINOperationQueue
- (instancetype)initWithMaxConcurrentOperations:(NSUInteger)maxConcurrentOperations
{
return [self initWithMaxConcurrentOperations:maxConcurrentOperations concurrentQueue:dispatch_queue_create("PINOperationQueue Concurrent Queue", DISPATCH_QUEUE_CONCURRENT)];
}
- (instancetype)initWithMaxConcurrentOperations:(NSUInteger)maxConcurrentOperations concurrentQueue:(dispatch_queue_t)concurrentQueue
{
if (self = [super init]) {
NSAssert(maxConcurrentOperations > 0, @"Max concurrent operations must be greater than 0.");
_maxConcurrentOperations = maxConcurrentOperations;
_operationReferenceCount = 0;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
//mutex must be recursive to allow scheduling of operations from within operations
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&_lock, &attr);
_group = dispatch_group_create();
_serialQueue = dispatch_queue_create("PINOperationQueue Serial Queue", DISPATCH_QUEUE_SERIAL);
_concurrentQueue = concurrentQueue;
//Create a queue with max - 1 because this plus the serial queue add up to max.
_concurrentSemaphore = dispatch_semaphore_create(_maxConcurrentOperations - 1);
_semaphoreQueue = dispatch_queue_create("PINOperationQueue Serial Semaphore Queue", DISPATCH_QUEUE_SERIAL);
_queuedOperations = [[NSMutableOrderedSet alloc] init];
_lowPriorityOperations = [[NSMutableOrderedSet alloc] init];
_defaultPriorityOperations = [[NSMutableOrderedSet alloc] init];
_highPriorityOperations = [[NSMutableOrderedSet alloc] init];
_referenceToOperations = [NSMapTable weakToWeakObjectsMapTable];
_identifierToOperations = [NSMapTable weakToWeakObjectsMapTable];
}
return self;
}
- (void)dealloc
{
pthread_mutex_destroy(&_lock);
}
+ (instancetype)sharedOperationQueue
{
static PINOperationQueue *sharedOperationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedOperationQueue = [[PINOperationQueue alloc] initWithMaxConcurrentOperations:MAX([[NSProcessInfo processInfo] activeProcessorCount], 2)];
});
return sharedOperationQueue;
}
- (id <PINOperationReference>)nextOperationReference
{
[self lock];
id <PINOperationReference> reference = [NSNumber numberWithUnsignedInteger:++_operationReferenceCount];
[self unlock];
return reference;
}
// Deprecated
- (id <PINOperationReference>)addOperation:(dispatch_block_t)block
{
return [self scheduleOperation:block];
}
- (id <PINOperationReference>)scheduleOperation:(dispatch_block_t)block
{
return [self scheduleOperation:block withPriority:PINOperationQueuePriorityDefault];
}
// Deprecated
- (id <PINOperationReference>)addOperation:(dispatch_block_t)block withPriority:(PINOperationQueuePriority)priority
{
return [self scheduleOperation:block withPriority:priority];
}
- (id <PINOperationReference>)scheduleOperation:(dispatch_block_t)block withPriority:(PINOperationQueuePriority)priority
{
PINOperation *operation = [PINOperation operationWithBlock:^(id data) { block(); }
reference:[self nextOperationReference]
priority:priority
identifier:nil
data:nil
completion:nil];
[self lock];
[self locked_addOperation:operation];
[self unlock];
[self scheduleNextOperations:NO];
return operation.reference;
}
// Deprecated
- (id<PINOperationReference>)addOperation:(PINOperationBlock)block
withPriority:(PINOperationQueuePriority)priority
identifier:(NSString *)identifier
coalescingData:(id)coalescingData
dataCoalescingBlock:(PINOperationDataCoalescingBlock)dataCoalescingBlock
completion:(dispatch_block_t)completion
{
return [self scheduleOperation:block
withPriority:priority
identifier:identifier
coalescingData:coalescingData
dataCoalescingBlock:dataCoalescingBlock
completion:completion];
}
- (id<PINOperationReference>)scheduleOperation:(PINOperationBlock)block
withPriority:(PINOperationQueuePriority)priority
identifier:(NSString *)identifier
coalescingData:(id)coalescingData
dataCoalescingBlock:(PINOperationDataCoalescingBlock)dataCoalescingBlock
completion:(dispatch_block_t)completion
{
id<PINOperationReference> reference = nil;
BOOL isNewOperation = NO;
[self lock];
PINOperation *operation = nil;
if (identifier != nil && (operation = [_identifierToOperations objectForKey:identifier]) != nil) {
// There is an exisiting operation with the provided identifier, let's coalesce these operations
if (dataCoalescingBlock != nil) {
operation.data = dataCoalescingBlock(operation.data, coalescingData);
}
[operation addCompletion:completion];
} else {
isNewOperation = YES;
operation = [PINOperation operationWithBlock:block
reference:[self nextOperationReference]
priority:priority
identifier:identifier
data:coalescingData
completion:completion];
[self locked_addOperation:operation];
}
reference = operation.reference;
[self unlock];
if (isNewOperation) {
[self scheduleNextOperations:NO];
}
return reference;
}
- (void)locked_addOperation:(PINOperation *)operation
{
NSMutableOrderedSet *queue = [self operationQueueWithPriority:operation.priority];
dispatch_group_enter(_group);
[queue addObject:operation];
[_queuedOperations addObject:operation];
[_referenceToOperations setObject:operation forKey:operation.reference];
if (operation.identifier != nil) {
[_identifierToOperations setObject:operation forKey:operation.identifier];
}
}
- (void)cancelAllOperations
{
[self lock];
for (PINOperation *operation in [[_referenceToOperations copy] objectEnumerator]) {
[self locked_cancelOperation:operation.reference];
}
[self unlock];
}
- (BOOL)cancelOperation:(id <PINOperationReference>)operationReference
{
[self lock];
BOOL success = [self locked_cancelOperation:operationReference];
[self unlock];
return success;
}
- (NSUInteger)maxConcurrentOperations
{
[self lock];
NSUInteger maxConcurrentOperations = _maxConcurrentOperations;
[self unlock];
return maxConcurrentOperations;
}
- (void)setMaxConcurrentOperations:(NSUInteger)maxConcurrentOperations
{
NSAssert(maxConcurrentOperations > 0, @"Max concurrent operations must be greater than 0.");
[self lock];
__block NSInteger difference = maxConcurrentOperations - _maxConcurrentOperations;
_maxConcurrentOperations = maxConcurrentOperations;
[self unlock];
if (difference == 0) {
return;
}
dispatch_async(_semaphoreQueue, ^{
while (difference != 0) {
if (difference > 0) {
dispatch_semaphore_signal(self->_concurrentSemaphore);
difference--;
} else {
dispatch_semaphore_wait(self->_concurrentSemaphore, DISPATCH_TIME_FOREVER);
difference++;
}
}
});
}
#pragma mark - private methods
- (BOOL)locked_cancelOperation:(id <PINOperationReference>)operationReference
{
PINOperation *operation = [_referenceToOperations objectForKey:operationReference];
BOOL success = [self locked_removeOperation:operation];
if (success) {
dispatch_group_leave(_group);
}
return success;
}
- (void)setOperationPriority:(PINOperationQueuePriority)priority withReference:(id <PINOperationReference>)operationReference
{
[self lock];
PINOperation *operation = [_referenceToOperations objectForKey:operationReference];
if (operation && operation.priority != priority) {
NSMutableOrderedSet *oldQueue = [self operationQueueWithPriority:operation.priority];
[oldQueue removeObject:operation];
operation.priority = priority;
NSMutableOrderedSet *queue = [self operationQueueWithPriority:priority];
[queue addObject:operation];
}
[self unlock];
}
/**
Schedule next operations schedules the next operation by queue order onto the serial queue if
it's available and one operation by priority order onto the concurrent queue.
*/
- (void)scheduleNextOperations:(BOOL)onlyCheckSerial
{
[self lock];
//get next available operation in order, ignoring priority and run it on the serial queue
if (_serialQueueBusy == NO) {
PINOperation *operation = [self locked_nextOperationByQueue];
if (operation) {
_serialQueueBusy = YES;
dispatch_async(_serialQueue, ^{
operation.block(operation.data);
for (dispatch_block_t completion in operation.completions) {
completion();
}
dispatch_group_leave(self->_group);
[self lock];
self->_serialQueueBusy = NO;
[self unlock];
//see if there are any other operations
[self scheduleNextOperations:YES];
});
}
}
NSInteger maxConcurrentOperations = _maxConcurrentOperations;
[self unlock];
if (onlyCheckSerial) {
return;
}
//if only one concurrent operation is set, let's just use the serial queue for executing it
if (maxConcurrentOperations < 2) {
return;
}
dispatch_async(_semaphoreQueue, ^{
dispatch_semaphore_wait(self->_concurrentSemaphore, DISPATCH_TIME_FOREVER);
[self lock];
PINOperation *operation = [self locked_nextOperationByPriority];
[self unlock];
if (operation) {
dispatch_async(self->_concurrentQueue, ^{
operation.block(operation.data);
for (dispatch_block_t completion in operation.completions) {
completion();
}
dispatch_group_leave(self->_group);
dispatch_semaphore_signal(self->_concurrentSemaphore);
});
} else {
dispatch_semaphore_signal(self->_concurrentSemaphore);
}
});
}
- (NSMutableOrderedSet *)operationQueueWithPriority:(PINOperationQueuePriority)priority
{
switch (priority) {
case PINOperationQueuePriorityLow:
return _lowPriorityOperations;
case PINOperationQueuePriorityDefault:
return _defaultPriorityOperations;
case PINOperationQueuePriorityHigh:
return _highPriorityOperations;
default:
NSAssert(NO, @"Invalid priority set");
return _defaultPriorityOperations;
}
}
//Call with lock held
- (PINOperation *)locked_nextOperationByPriority
{
PINOperation *operation = [_highPriorityOperations firstObject];
if (operation == nil) {
operation = [_defaultPriorityOperations firstObject];
}
if (operation == nil) {
operation = [_lowPriorityOperations firstObject];
}
if (operation) {
[self locked_removeOperation:operation];
}
return operation;
}
//Call with lock held
- (PINOperation *)locked_nextOperationByQueue
{
PINOperation *operation = [_queuedOperations firstObject];
[self locked_removeOperation:operation];
return operation;
}
- (void)waitUntilAllOperationsAreFinished
{
[self scheduleNextOperations:NO];
dispatch_group_wait(_group, DISPATCH_TIME_FOREVER);
}
//Call with lock held
- (BOOL)locked_removeOperation:(PINOperation *)operation
{
if (operation) {
NSMutableOrderedSet *priorityQueue = [self operationQueueWithPriority:operation.priority];
if ([priorityQueue containsObject:operation]) {
[priorityQueue removeObject:operation];
[_queuedOperations removeObject:operation];
if (operation.identifier) {
[_identifierToOperations removeObjectForKey:operation.identifier];
}
return YES;
}
}
return NO;
}
- (void)lock
{
pthread_mutex_lock(&_lock);
}
- (void)unlock
{
pthread_mutex_unlock(&_lock);
}
@end