GCD Concurrent Queues
This is the third post in a series about Grand Central Dispatch.
If serial queues are a better replacement for mutexes (and more), then concurrent queues are a better replacement for threads (and more).
A concurrent queue allows you to enqueue blocks that will start running without waiting for the previous blocks to finish.
Run the following program several times:
#import <Foundation/Foundation.h>
void print(int number) {
for (int count = 0; count < 10; ++count) {
NSLog(@"%d", number);
}
}
int main(int argc, const char * argv[]) {
dispatch_queue_t queue = dispatch_queue_create("My concurrent queue", DISPATCH_QUEUE_CONCURRENT);
@autoreleasepool {
for (int index = 0; index < 5; ++index) {
dispatch_async(queue, ^{
print(index);
});
}
}
dispatch_main();
return 0;
}
dispatch_async()
tells GCD to enqueue a block, but not to wait until the block is done before moving on. This allows us to quickly “toss” five blocks onto the concurrent queue we just created.
When the first block is enqueued, the queue is empty, so it begins running the same way it would if the queue were serial. However, when the second block is enqueued, it too will run even though the first block hasn’t finished running. The same goes for the third block, the fourth, and the fifth—they all run at the same time.