我对使用dispatch_after
和dispatch_semaphore_t
一起执行一些任务并在每个线程之间等待一段时间感到好奇。
我使用以下代码:
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3ull * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_after(time, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"blk01");
dispatch_semaphore_signal(semaphore);
});
dispatch_after(time, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"blk02");
dispatch_semaphore_signal(semaphore);
});
dispatch_after(time, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"blk03");
dispatch_semaphore_signal(semaphore);
});
我在 3 秒后执行线程,而不是预期的延迟。
我究竟做错了什么?有没有其他方法可以在 dispatch_semaphore_t 中执行线程,每个线程执行之间有延迟时间?