【发布时间】:2012-08-02 19:57:00
【问题描述】:
int total = 0; // these are globals..
BOOL dispatchCalled = NO; //
-(void) callDispatch
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
dispatchCalled = YES;
NSLog(@"Total, after 300ms, is %i", total);
});
}
-(void)play // this is my "main" method..
{
NSLog(@"app starts running");
[self callDispatch];
while(!dispatchCalled)
{
total++;
}
[self callDispatch];
}
控制台:
2012-08-02 20:36:05.357 MyProject[8245:1a07] app starts running
2012-08-02 20:36:05.693 MyProject[8245:3d03] Total, after 300ms, is 11513522
2012-08-02 20:36:05.993 MyProject[8245:3d03] Total, after 300ms, is 11513523
当 callDispatch 中包含的方法第一次执行时,while 循环有时间执行 11513522 次。此时,while 循环的条件设置为YES,while 循环不应再执行。但是,它会在确认由调度方法条件更新之前再执行一次。这是为什么呢?
是不是因为 callDispatch 中包含的方法会并发/并行 与 while循环执行,这就解释了为什么while循环需要多一个循环-循环确认更新的条件?
【问题讨论】:
-
在
dispatch_after块内设置断点——当它到达那里时,调试器会告诉你它在哪个线程上。
标签: iphone objective-c ios concurrency timer