Regarding multiple threads on the iPhone
I have a question. My case study is that I have two big SQLite databases and I want to use threads (meaning 2 processes simultaneously). Did it 开发者_StackOverflow社区work well? I have written the following code:
NSAutoreleasePool *dbPool;
dbPool = [[NSAutoreleasePool alloc] init];
/* All Database work is performed here */
[dbPool release];
Please guide me. Am I doing this correctly or not? Should I use a pool to drain or release?
And in that way is this using concurrent processes, meaning it's also the same behavior as multitasking?
Thanks in advance!
Yep, you're doing it right. Each of your new thread needs own autorelease pool.
Regarding to your question about release / drain of pool, recommended is drain message.
What do you mean by sqlite database? How do you access it? If you access it via CoreData, you have keep following in your memory:
- you need one NSManagedObjectContext per thread,
- do not pass NSManagedObjects to another thread, just pass object ID,
- before you pass object ID to another thread, save it in thread where it was modified / created before passing it.
There are more rules, but these are basic ones.
Multitasking means that you can run more applications in one time. Multithreading (= your case) means that your application does use more threads to achieve its task.
A common approach for user interface or other heavy object management work is to surround your code like you're doing, but you should be using drain
:
NSAutoreleasePool *dbPool = [[NSAutoreleasePool alloc] init];
// do your work
[dbPool drain];
A lot of detail on NSAutoreleasePool
is available here and a previous Stack Overflow answer here. Basically the work you're doing inside the pool, if set to autorelease
, will be released once the pool drains. This can increase performance when working with certain classes that produce autoreleased instances. If you want full and immediate control though, you can release
each object you're working with once it's no longer needed and ditch the pool altogether.
As to your multithreading questions I'm not sure if I understand what you're asking but nonetheless using the pool is a solid approach even in a background thread. This is assuming that the objects you're working with in the thread aren't somehow also used in another (since you might have an accidental release).
精彩评论