Created
July 2, 2019 09:19
-
-
Save qy1010/375b6ae08efab2262f3182283c46ab28 to your computer and use it in GitHub Desktop.
异步方法同步执行:信号量dispatch_semaphore
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
- (NSInteger)methodSync { | |
NSLog(@"methodSync Begin"); | |
__block NSInteger result = 0; | |
//使用信号量dispatch_semaphore | |
dispatch_semaphore_t sema = dispatch_semaphore_create(0); | |
[self methodAsync:^(NSInteger value) { | |
result = value; | |
dispatch_semaphore_signal(sema); | |
}]; | |
// 这里本来同步方法会立即返回,但信号量=0使得线程阻塞 | |
// 当异步方法回调之后,发送信号,信号量变为1,这里的阻塞将被解除,从而返回正确的结果 | |
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment