Skip to content

Instantly share code, notes, and snippets.

@qy1010
Created July 2, 2019 09:19
Show Gist options
  • Save qy1010/375b6ae08efab2262f3182283c46ab28 to your computer and use it in GitHub Desktop.
Save qy1010/375b6ae08efab2262f3182283c46ab28 to your computer and use it in GitHub Desktop.
异步方法同步执行:信号量dispatch_semaphore
- (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