我很好奇使用dispatch_after
和dispatch_semaphore_t
一起執行一些任務,並在每個線程之間等待一段時間。如何讓dispatch_after和dispatch_semaphore_t在GCD中一起工作?
我使用下面的代碼:
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中的線程,每個線程執行之間有延遲時間?
它就像一個魅力,沒有什麼特別與dispatch_semaphore_t只是好奇,並有正確的方式來做到這一點。 – chroman
如果塊執行超過setuped時間,該怎麼辦? –