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.
Concurrency and multithreading are a core part of iOS development. Let's dive into what makes them so powerful, and how we can leverage them in our own Cocoa Touch applications. Concurrency is the notion of multiple things happening at the same time.
Apple provides 2 main APIs for writing multithreaded code: Grand Central Dispatch(GCD) and Operation. Behind the scenes, they use a concept known as thread pool, meaning that those API manages a large number of threads and when a task is ready to be executed, it grabs one thread from the pool to take care of the task.
Multithreading is nothing but performing tasks concurrently, by scheduling them on multiple threads to improve the application's performance. Concurrency in single-core processor vs multi-core processor (Author)
1)Dispatch queues. 2)Threads. 3)Operation queues.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With