Last active
June 13, 2016 13:36
-
-
Save thornpig/a5f6695cae79c96bbd211bc2f8b74f45 to your computer and use it in GitHub Desktop.
Synchronize asynchronous task with NSRunloop or diaptch_semaphore
This file contains hidden or 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
| //with semaphore | |
| self.sem = disptach_semaphore_create(0); | |
| [someAsyncTask start]; //someAsyncTask needs to call dispatch_semaphore_signal(self.sem) after the its work is done. | |
| disptach_semaphore_wait(self.sem, DISPATCH_TIME_FOREVER); | |
| NSLog(@"task is done!"); | |
| //with NSRunloop | |
| self.taskIsDone = NO; | |
| [someAsyncTask start]; //someAsyncTask needs to set self.taskIsDone = YES after the work is done. | |
| while (!self.taskIsDone) | |
| { | |
| [[NSRunloop currentRunloop] runMode: NSDefaultRunloopMode beforeDate: [NSDate distantFuture]]; | |
| } | |
| NSLog(@"task is done!"); | |
| The NSRunloop method won't block the calling thread, while the semaphore method could block the calling thread if | |
| the dispatch_semaphore_signal(self.sem) is assgined to be executed on the calling thread. For example, if the calling | |
| thread is the main thread, and dispatch_semaphore_signal(self.sem) is setup to be triggered by notification, | |
| the execution will never happen because the notification center usually uses the main thread to post notification but | |
| the main thread is blocked by disptach_semaphore_wait. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment