Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created September 11, 2014 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/18e41721a0be7924c99b to your computer and use it in GitHub Desktop.
Save chriseidhof/18e41721a0be7924c99b to your computer and use it in GitHub Desktop.
nilResultAfterTimeOut
id nilResultAfterTimeOut(int64_t timeoutInNanoSeconds, ResultBlock block) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_time_t timeoutTime = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds);
__block id result = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
result = block();
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, timeoutTime);
return result;
}
// Examples
id result = nilResultAfterTimeOut(1 * NSEC_PER_SEC, ^id{
sleep(2);
return @5;
}); // returns nil
id result = nilResultAfterTimeOut(3 * NSEC_PER_SEC, ^id{
sleep(2);
return @5;
}); // returns @5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment