当我通过 dispatch_async 将两个块提交到串行队列中时,它是否确保第二个在第一个之后运行:
- dispatch_async(serial_queue, b1);
- dispatch_async(serial_queue, b2);
我们能保证 b1 在 b2 之前运行吗?
以下是完整的源代码部分:
#define COUNTER 10000
m_value = 0;
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t queue = dispatch_queue_create("myqueue", NULL);
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < COUNTER; ++i) {
dispatch_group_async(group, globalQueue, ^() {
dispatch_async(queue, ^() {
++m_value;
});
});
}
dispatch_group_notify(group, queue, ^() {
NSLog(@"m_value Actual: %d Expected: %d", m_value, COUNTER);
});
dispatch_release(queue);
dispatch_release(group);
queue = nil;
group = nil;
return YES;
我们可以保证 m_value == COUNTER 总是吗?谢谢