如果还未执行的子线程可以用dispatch_cancel(object)来取消,但是一般面试官会追问如果正在执行的线程呢?
听别人说起过用return可以中止测试了一下是可以的,下面给出简单实现过程
__block BOOL gcdFlag= NO;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (long i=0; i<10000; i++) {
NSLog(@"正在执行第i次:%ld",i);
sleep(1);
if (gcdFlag==YES) {
NSLog(@"终止");
return ;
}
};
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(10 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
NSLog(@"我要停止啦");
gcdFlag = YES;
});
2018-04-20 10:08:00.399147+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:0
2018-04-20 10:08:01.400996+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:1
2018-04-20 10:08:02.405490+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:2
2018-04-20 10:08:03.411145+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:3
2018-04-20 10:08:04.413742+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:4
2018-04-20 10:08:05.417971+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:5
2018-04-20 10:08:06.422405+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:6
2018-04-20 10:08:07.428046+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:7
2018-04-20 10:08:08.430766+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:8
2018-04-20 10:08:09.431861+0800 nsoperationQueueDemo[10842:1099177] 正在执行第i次:9
2018-04-20 10:08:10.399195+0800 nsoperationQueueDemo[10842:1099115] 我要停止啦
2018-04-20 10:08:10.435079+0800 nsoperationQueueDemo[10842:1099177] 终止
网友评论