Created
November 10, 2010 19:04
-
-
Save rsms/671329 to your computer and use it in GitHub Desktop.
Sleeping barber with GCD (Grand Central Dispatch)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main (int argc, const char * argv[]) { | |
dispatch_queue_t waitingChairs = dispatch_queue_create("waitingChairs", 0); | |
dispatch_queue_t barber = dispatch_queue_create("barber", 0); | |
dispatch_semaphore_t semaphore = dispatch_semaphore_create(3); | |
NSInteger ident = 0; | |
while (++ident) { | |
if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) != 0) { | |
printf("Customer %d turned away\n", ident); | |
continue; | |
} | |
dispatch_async(waitingChairs, ^{ | |
printf("Customer %d taking a seat\n", ident); | |
dispatch_async(barber, ^{ | |
dispatch_semaphore_signal(semaphore); | |
printf("Shave and a haircut for customer %d\n", ident); | |
}); | |
}); | |
} | |
dispatch_release(waitingChairs); | |
dispatch_release(barber); | |
dispatch_release(semaphore); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment