Created
May 4, 2018 03:30
-
-
Save zhangkn/79a3099f58438796bc5254c632b2034a to your computer and use it in GitHub Desktop.
使用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
/** | |
二、dispatch信号量(dispatch semaphore)和 dispatch_sync(dispatch_get_main_queue() ----威力强大,建议使用递归,在block中触发退出条件 | |
1. 创建信号量,可以设置信号量的资源数。0表示没有资源,调用dispatch_semaphore_wait会立即等待。 | |
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); | |
2. 等待信号,可以设置超时参数。该函数返回0表示得到通知,非0表示超时。 | |
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); | |
3. 通知信号,如果等待线程被唤醒则返回非0,否则返回0。 | |
dispatch_semaphore_signal(semaphore); | |
一、 使用dispatch信号量是如何实现同步: | |
尤其用于将异步的block 变成同步中 | |
*/ | |
+ (void)run{ | |
while (@"condition") { | |
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);//创建信号 | |
dispatch_semaphore_wait(semaphore,dispatch_time(DISPATCH_TIME_NOW, (int64_t)( 16 * NSEC_PER_SEC)));//保证是同步的 | |
[self setupSwitchIp:^(NSString *errorMsg, id result) {//异步的block中激活信息号,来保证程序的同步执行 | |
dispatch_semaphore_signal(semaphore);//激活信号 | |
}]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment