Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using a dispatch semaphore with block

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.00k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: