开发者

OK to launch background threads from other background threads? (NSObj)

This question is for those of you who, unlike myself, truely understand multi-threading in cocoa apps. Here, briefly, is the situation:

Situation:

My app achieves concurrency by using the methods provided in NSObject. Please tell me if it is OKAY to do the following:

1) My main view controller launches some work in the background to free up the UI:

[self performSelectorInBackground:@selector(loadImages:) withObject:nil];

2) The background work divides its task into several smaller tasks on more background threads so that each task is updated as it finishes (as opposed to when all tasks finish):

[self performSelectorInBackground:@selector(loadOneImage:) withObject:nil];

Rationale:

This was the only way I could invent to get individual tasks (loading/drawing of custom UIViews) in a set to update in UI AS each is completed. Otherwise, all tasks only get updat开发者_运维百科ed when the last task in the group has completed...


yes, you may use performSelectorInBackground:... calls to spawn secondary threads from secondary threads.

if you have a lot threads to spawn (in this manner), consider an NSOperationQueue. Otherwise, you may end up with a ton of background threads. 100 threads (for example), each loading one image in a mobile device is not a good use of resources - nor will it be responsive. NSOperationQueue allows you to cap the max number of threads/workers, and reuses worker threads.

note: '100 threads' was used because the number is far beyond logical for the hardware (the question is tagged iPhone). if your image loading is all in memory, just use a serial (1 worker at a time) NSOperationQueue - NSOperations may specify priority. if images are being downloaded, then you may want to stick to 4 or less.

things are different on OS X, where there are more cores and resources available, so these numbers will change as the hardware platform change. on OS X, you can successfully use 100 threads in one app, although it is unusual to need anything near that many threads for most apps.


There's nothing wrong with this approach as far as I can see. According to the doc, performSelectorInBackground:withObject: just spawns another thread and executes your selector there. It doesn't list any limitations. Just don't forget to set up autorelease pools in each method that you call via performSelectorInBackground:withObject: to not leak any memory.


One critical condition you should make sure. Both threads which are running in background should not have any dependency. If they have, then you may end up in inconsistency.

So beter if you go for operation queues rather than spawning thread from another background thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜