Skip to content

Instantly share code, notes, and snippets.

@zhangkn
Created May 4, 2018 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkn/79a3099f58438796bc5254c632b2034a to your computer and use it in GitHub Desktop.
Save zhangkn/79a3099f58438796bc5254c632b2034a to your computer and use it in GitHub Desktop.
使用dispatch信号量是如何实现同步
/**
二、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