Kos*_*s.N 30 objective-c grand-central-dispatch
我无法暂停gcd查询.以下是一些演示此问题的代码:
static dispatch_queue_t q=nil;
static void test(int a){
if(q){
dispatch_suspend(q);
dispatch_release(q);
q=nil;
}
q=dispatch_get_global_queue(0,0);
dispatch_async(q,^ {
while(1){NSLog(@"query %d",a);sleep(2);}
});
}
int main(int argc, const char* argv[]){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
test(1);
//blah blah blah
test(2);
while(1){}
[pool release];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的是在第二次调用函数测试时暂停,释放和重新初始化查询q,但显然我的代码是错误的,并且查询q的两个实例都继续运行.
非常感谢您的帮助,谢谢.
Rya*_*yan 41
在实际调用dispatch_suspend()之前异步调度到队列的任何块都将在挂起生效之前运行.在您的代码中,您将异步触发一堆块,因此当您调用test(2)时,某些块可能仍在队列中,并且这些块将被执行.
如果您希望能够取消正在运行的作业,则需要按照自己的逻辑进行操作.GCD故意不公开真正的取消API.你可以这样做:
@interface Canceller
{
BOOL _shouldCancel;
}
- (void)setShouldCancel:(BOOL)shouldCancel;
- (BOOL)shouldCancel;
@end
@implementation Canceller
- (void)setShouldCancel:(BOOL)shouldCancel {
_shouldCancel = shouldCancel;
}
- (BOOL)shouldCancel {
return _shouldCancel;
}
@end
static void test(int a){
static Canceller * canceller = nil;
if(q){
[canceller setShouldCancel:YES];
[canceller release];
dispatch_suspend(q);
dispatch_release(q);
q=nil;
}
canceller = [[Canceller alloc] init];
q=dispatch_get_global_queue(0,0);
dispatch_async(q,^ {
while(![canceller shouldCancel]){NSLog(@"query %d",a);sleep(2);}
});
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,每个块将保持对一个对象的引用,该对象知道它是否应该停止工作.
| 归档时间: |
|
| 查看次数: |
31268 次 |
| 最近记录: |