Blocks are a language-level feature, which allow us to create distinct segment of code.
there are three way to recognize the semaphore.
dispatch_semaphore_create =>
creates a semaphore with initial value
dispatch_semaphore_signal => increments the semaphore (send a semaphore signal)
dispatch_semaphore_wait => decrements the semaphore (wait for a semaphore signal)
So, it means we can use semaphore to wait for a blocks completion. we have access the dispatch semaphore by following way.
SINGLE BLOCK
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
MULTIPLE BLOCKS
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
}];
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
BLOCK IN BLOCK
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
}];
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
0 Comment(s)