【发布时间】:2013-07-13 23:52:50
【问题描述】:
我想确保两个队列最终在不同的线程上执行。理想情况下,我想确保它们是串行队列。特别是,在下面的示例中,如果两个队列在同一个线程上运行,doStuff 将无限期地忙于等待。我将不得不转向显式线程还是可以在这里挽救 GCD 的使用?
- (void)foo {
self.responseQueue = dispatch_queue_create("com.blah.response", DISPATCH_QUEUE_SERIAL);
self.requestQueue = dispatch_queue_create("com.blah.request", DISPATCH_QUEUE_SERIAL);
dispatch_async(self.requestQueue, ^{
[self doStuff];
});
}
- (BOOL)doStuff {
BOOL __block waiting = YES;
self.responseBlock = ^{
waiting = NO;
};
[self performRequest];
while (waiting) {
// realize could use dispatch_semaphore (busy waiting just to illustrate point).
sleep(1);
}
[self doStuffRequiringResponseCompletion];
// I realize it would be sensible to
// 1) Not block in the above while loop.
// 2) Call |doStuffRequiringResponseCompletion| after |receivedResponse|.
// I don't want to do this.
}
// method called on arbitrary thread
- (void)receivedResponse {
// stuff
dispatch_async(self.responseQueue, self.responseBlock);
}
另请参阅:Is there any reason to not use sleep in a Grand Central Dispatch queue??
【问题讨论】:
-
performRequest 神奇地调用 receivedResponse 并不直观。如果 performRequest 失败,您应该使用超时。当请求/响应是同一串行操作的一部分时,为什么要使用两个串行队列进行请求/响应?为什么是全局响应块?为什么要异步和阻塞? GCD 的存在是为了避免显式线程的复杂性。如果您解释您的用例,您将获得更好设计的建议。
标签: objective-c grand-central-dispatch