【发布时间】:2017-08-31 07:14:02
【问题描述】:
我有一个与 LLVM 编译器的优化级别有关的有趣问题。我正在使用:
- Xcode 8.2.1
- LLVM 8.0
最好用示例代码来解释。我将问题归结为一个简单的objective-c 类。请先看下面的代码:
@interface Foo() {
BOOL is_loading;
}
@end
@implementation Foo
- (void)test {
printf("started loading \n");
// set loading flag to YES
is_loading = YES;
// schedule a timer to fire in 2 seconds, to simulate the end of loading
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(timerFired)
userInfo:nil
repeats:NO];
// wait asynchronously until loading flag is set to NO
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (is_loading) {
// loop until timer event modifies is_loading flag
}
printf("finished loading \n");
});
}
- (void)timerFired {
printf("timer fired \n");
// set loading flag to NO
is_loading = NO;
}
@end
如果你实例化类Foo并调用load方法,它将模拟一个加载进度并异步观察is_loading标志以确定加载是否完成。
之后,控制台输出会是这样的:
started loading
timer fired
finished loading
但是如果你打开编译器优化,你会看到这样的输出:
started loading
timer fired
显然,while 循环永远不会结束,执行无法到达下一个 printf() 消息。
我是否遗漏了导致这种情况发生的明显原因,还是可能是优化器错误?
【问题讨论】:
标签: ios objective-c xcode llvm compiler-optimization