2
votes

I know that i can execute tasks asynchronously with dispatch_async and dispatch_get_global_queue.

But how many threads dispatch_async create? What should i do to execute exactly N (no more, no less) threads with GCD, and performe some tasks on them? After execution of task i need to add new task in released thread, maybe in complitation block of previous task.

Or maybe i can control the count of threds with NSOperationQueue? I know that it has property maxConcurrentOperationCount, but it control only maximum limit of tasks. So, Can I be sure that NSOperationQueue creates no less than 8 threads, in case when i set maxConcurrentOperationCount = 8 and add 12 operations to the NSOperationQueue?

Thank you very much!

4
why? the reason of using GCD is to save save us from finding optimal thread count. If you want exactly N threads, then create them yourself using NSThread - Bryan Chen
there is no reason in practice, it is just for research. - BergP
maxConcurrentOperationCount is just a maximum. It could create fewer. If you need precise control over the number of threads, then you'll have to manage them yourself. - ipmcc
@xlc The reason this would be useful is that if your apps dispatches too many operations, you tie up the system, end up blocking the main queue in the process. It strikes me as a fairly glaring omission in GCD and why I now generally use operation queues. This omission defeats many of the benefits of GCD for massively parallel operations. - Rob
@Rob i know that in osx there is a limit of maximum 64 worker threads, not sure about ios. also GCD will only spawn new threads if CPU is not fully utilized (thats whole poiont of using GCD). i agree it is possible to create have 64 busy worker threads using GCD but it is unlikely to happen if you use it correctly. - Bryan Chen

4 Answers

5
votes

You should look into NSThread. It's the way to go if you need fine grain control over exactly the number of threads you want to have running.

4
votes

Subclass NSOperation for the tasks you want to do and put them into an NSOperationQueue. You can set the number of concurrent operations on the queue.

NSOperationQueue *q = [[NSOperationQueue alloc] init];
q. maxConcurrentOperationCount = N;
1
votes

Queue concept is different from thread. Go through NSThread class. Since NSOperation uses GCD you can't set thread from here. You can merge the NSThread and NSOperation creating and passing different threads.
But why would you do that? more thread doesn't mean more speed, usually is the opposite with a lot of concern about memory, locking, concurrency etc.
You should have a very specific reason.

0
votes

If you want to control the max count of threads when using gcd, you can make use of DispatchSemaphore. Firstly, create a semaphore with the max count, secondly at the beginning of a task, semaphore.wait(), finally at the end of a task, semaphore.signal().