I have some data calculation method (let it be "myMethod:"), and I want to move the call to another thread because I don't want to block my main UI functionality. So, started to do some research on how to call my method on another thread. As far as I see, currently, there are a lot of different ways for doing that. Here's a list:
a) using pure threads (available since iOS 2.0):
[NSThread detachNewThreadSelector:@selector(myMethod:) toTarget:self withObject:_myParamsArray];
b) using a simple shortcut (available since iOS 2.0). Available from inherited NSObject but the method belongs to NSThread class too:
[self performSelectorInBackground:@selector(myMethod:) withObject:_myParamsArray];
c) using a new approach of Grand Central Dispatch queues (available since iOS 4.0):
dispatch_async(dispatch_get_global_queue(0, 0),
^ {
[self myMethod:_myParamsArray];
});
d) somehow, using some classes such as NSOperation, NSBlockOperation or NSOperationQueue, though not sure how exactly to do it (some example would be appreciated)
Currently, I have used case "b" but curious about pros and cons and other related suggestions on that.
==========================
Answer:
Usually, you would prefer the GCD approach.
It's simpler when it comes to synchronization/locking than pure threads (NSThread - pthread), and it may be more accurate in a performance perspective.
When using pure threads, the problem is you may have performance issues, depending on the number of available cores/processors.
For instance, if you have only one core, creating many threads may slow down your application, because the CPU will spend most of its time switching from one thread to another, saving the stack, registers, etc.
On the other hand, if you have a lot of cores available, it may be nice to create a lot of different threads.
This is where GCD helps, as it manages this for you. It will create the appropriate number of threads, based on the available system resources, to guarantee an optimal utilization, and schedule your actions appropriately.
However, for that reason, tasks launched with GCD may not be real-time.
So if you REALLY needs that a detached task runs immediately, use an explicit threads. Otherwise, use GCD.
Hope this will help you : )
EDIT
A note about
performSelectorInBackground
: it simply creates a new thread. So there's basically no difference with the NSThread approach.
EDIT 2
NSOperation related stuff are a bit different. On Mac OS X, they are implemented using GCD since version 10.6. Previous versions uses threads.
On iOS, they are implemented using threads only.
Reference
All of this is very well explained in the Concurrency Programming Guide. It discusses the GCD and thread approaches, with a lot of details about the uses and implementations.
If you haven't read it already, you should take a look.
Original post:
0 comentaris:
Publica un comentari a l'entrada