3

我有以下代码:

- (void)test_with_running_runLoop {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSTimeInterval checkEveryInterval = 0.05;

    NSLog(@"Is main queue? : %d", dispatch_get_current_queue() == dispatch_get_main_queue());

    dispatch_async(dispatch_get_main_queue(), ^{
        sleep(1);
        NSLog(@"I will reach here, because currentRunLoop is run");
        dispatch_semaphore_signal(semaphore);
    });

    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:checkEveryInterval]];

    NSLog(@"I will see this, after dispatch_semaphore_signal is called");
}

- (void)test_without_running_runLoop {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSLog(@"Is main queue? : %d", dispatch_get_current_queue() == dispatch_get_main_queue());

    dispatch_async(dispatch_get_main_queue(), ^{
        sleep(1);
        NSLog(@"I will not reach here, because currentRunLoop is not run");
        dispatch_semaphore_signal(semaphore);
    });

    NSLog(@"I will just hang here...");
    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW));

    NSLog(@"I will see this, after dispatch_semaphore_signal is called");
}

产生以下内容:

Starting CurrentTests/test_with_running_runLoop
2012-11-29 08:14:29.781 Tests[31139:1a603] Is main queue? : 1
2012-11-29 08:14:30.784 Tests[31139:1a603] I will reach here, because currentRunLoop is run
2012-11-29 08:14:30.791 Tests[31139:1a603] I will see this, after dispatch_semaphore_signal is called
OK (1.011s)

Starting CurrentTests/test_without_running_runLoop
2012-11-29 08:14:30.792 Tests[31139:1a603] Is main queue? : 1
2012-11-29 08:14:30.797 Tests[31139:1a603] I will just hang here...

我的问题是相互关联的:

  1. 如果我理解正确,主队列 (dispatch_get_main_queue()) 是一个串行队列。我用 dispatch_semaphore_wait 阻塞了主队列/主线程,那么为什么我会在第一个测试用例中看到“我会到达这里,因为 currentRunLoop 正在运行” (我对第二种情况很好 - 据我了解,确实如此,它应该是什么)?

  2. 在当前执行任务被阻塞的情况下,串行队列如何在当前任务解锁之前调度下一个任务(哦,这个神秘的 runLoop:beforeDate:)?

我想听听详细全面的答案,因为非常非常多的事情(这里也是如此)取决于这个问题!

更新:除了接受的答案之外,这个 SO 主题对这个问题有很好的回答:Pattern for unit testing async queue that calls main queue on completion

4

1 回答 1

6

因为主线程上的默认 runloop 具有特殊行为,即在运行时,它还为主调度队列进行处理。在这种情况下,您实际上并没有阻塞,因为您要dispatch_semaphore_wait立即超时,它正在执行此操作(返回非零,它的计算结果if为真)-因此您运行 while 循环,在其中驱动当前运行循环,因此您的排队块被执行。

But my answer is broad because I'm not sure what part you're surprised by.

于 2012-11-29T07:00:13.920 回答