I’m getting curious about using dispatch_after and dispatch_semaphore_t together to execute some tasks and wait some time between each thread.
I use the following code:
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);
});
I’m getting the execution of threads after 3 seconds, not with the expected delay.
What am I doing wrong? Is there any other way to execute threads in dispatch_semaphore_t with delay time between each thread execution?
If you want to execute three blocks serially (not concurrently), and you want to pause between blocks, there are simpler ways than using a semaphore. The simplest is to just create a serial queue and put a
sleep(orusleep) at the beginning or end of each block:Putting
sleepin your blocks is very simple, but ties up a thread. That probably doesn’t matter unless you’re creating a lot of queues and sleeping on many of them.If you tell us why you think you need a semaphore, perhaps we can offer you a better alternative or advice on how to use it properly.