I want show you simple way to create multi-thread calculations in few strings of code.
Simple collection of operations. But remember about blocks specifications and use proper storage type.
1
2 3 4 5 6 7 |
NSMutableArray *operations = [NSMutableArray array];
for (...) { NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ // calculation }]; [operations addObject:operation]; } |
If you don’t like blocks, you can easily make a subclass of NSOperation and overwrite main function.
Now time to create queue for operations, so just create instance of NSOperationQueue.
And in maxConcurrentOperationCount property you need setup proper value. For example 2, if you want to use just 2 concurrent threads for your calculations and continue in normal state with others operations in another threads.
In this case waitUntilFinished should be NO.
But if you want to use max threads of CPU, setup NSOperationQueueDefaultMaxConcurrentOperationCount to maxConcurrentOperationCount and YES to waitUntilFinished. Like in example below:
1
2 3 4 5 |
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:....]; [queue addOperations:operations waitUntilFinished:YES]; [queue waitUntilAllOperationsAreFinished]; [operations removeAllObjects]; |
If this is set, it will choose an appropriate value based on the number of available processors and other relevant factors.
1
2 3 |
enum {
NSOperationQueueDefaultMaxConcurrentOperationCount = -1 }; |
NSOperationQueueDefaultMaxConcurrentOperationCount: The default maximum number of operations is determined dynamically by the NSOperationQueue object based on current system conditions.
That it! It’s so simple today.