Reputation: 478
I want to parse an EPUB file, after read the file into memory, I need to parsing the content. The book might have more than 10 chapters; I created NSOperation instance for each chapter, and run concurrency, all on CPU calculations.
Should I have 2 threads, each with 5 chapters to process, or have 10 threads for each? which one is more efficient? Different devices would have different strategy?
Upvotes: 1
Views: 203
Reputation: 718788
Should I have 2 threads, each with 5 chapters to process, or have 10 threads for each? which one is more efficient?
What you should do is create a worker pool with maybe 2 or 3 threads, a queue, and have each thread pull one task at a time from the queue and execute it. The number of worker threads should be proportional to the number of cores on your device. (The actual optimal number will depend on whether the processing tasks need to do I/O that could result in the thread blocking for a time ...)
Creating a thread for each chapter consumes resources (thread stacks) for no speedup. You only get speedup if you have enough physical cores that the threads can actually be executing in parallel on the different cores.
Preallocating the chapters to the threads is not a good idea because, you might allocate a significantly smaller workload to one thread than the other.
Actually, if it is possible to cheaply get a good estimate of how much work there is in processing each chapter, you may be able to do a better job of scheduling the workload across the threads than a simple queue. But it is debatable whether it is worth the effort.
Upvotes: 4