I have an application which utilizes OpenEars and the Flite library. The problem is that the Flite library is resource intensive and it's freezing up my app. I suspect that running Flite on a background thread will fix things, but I have no idea how to do so.
That said, how do I implement a background thread in iOS?
I'd appreciate if anyone can point me to some tutorials, share some sample code, or any general advice that would help me solve this problem.
The Concurrency Programming Guide by Apple is a nice reading. Concurrent programming is not something you might want to pick up by copying some sample code from the web and hacking until you are happy. It’s good to know the options and principles to save yourself from trouble.
Revisiting the answer after some time, nowadays you almost can’t go wrong using Grand Central Dispatch. Running a task in background looks like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doSomeLongTask]; // 1
dispatch_async(dispatch_get_main_queue(), ^{
[self longTaskDidFinish]; // 2
});
});
The long task (1) will run on some background thread and there’s no catch that I am aware of, ie. there’s already an autorelease pool in that thread, you don’t have to care about run loops etc. After the task finishes the code calls -longTaskDidFinish
on the main thread (2), so that you can update UI or whatever else. This is an often used idiom.