I have 5 functions that need to be run on a separate thread. Grand Central Dispatch is supposed to be more efficient than threads so I decided to use it. Each function has an infinite while loop - while(true)- that runs throughout the duration of the program. So the function doesn't return until the program exists. The thing is though, GCD doesn't run queues at the same time - it runs each queu one at a time. When the first queu completes, it begins the second queu. If I put each function on a queue, only one will run because Grand Central Dispatch will be waiting for the first one to return to run the next one but the function will never return (since it is an infinite while loop). Is there any way I can use GCD with infinite loop functions? Or should I just use threads?
Xcode 3.2.6 on Mac OSX Snowleopard 10.6.8.
Boy, lots of confused/conflciting answers so far!
First off, there is NO reason for you to use threads here. None. Using GCD, even for "long running" operations, is perfectly fine. If all that you're doing from said operations is reading data and then doing something with the data then you should certainly use dispatch sources or dispatch_io since that's what they're for and they can greatly simplify your code, also only creating threads as necessary, but if you are really attached to the notion of having multiple, long-running parallel operations then simply wrap each of those operations into a block and then dispatch those blocks to one of the global concurrent queues. They will run in parallel. If what you have is more along the lines of "multiple workflows", in which each workflow represents a distinct chain of operations that need to happen serially but in parallel to the other workflows, then create a serial queue for each workflow and the independent serial queues will run concurrently with respect to one another. It's just that simple! GCD often confuses folks who are expecting things to be more complicated, or come from a classic threading background and trying to map one concept to the other. Don't do that and you'll have a far easier time. :)
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