gcd 两个线程交替打印数组
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray * array = [[NSMutableArray alloc]init];
for(int i = 0; i < 100; i++){
[array addObject: [NSNumber numberWithInt:i]];
}
// 闭包捕获变量
__block int i = 0;
dispatch_semaphore_t source1 = dispatch_semaphore_create(0);
dispatch_semaphore_t source2 = dispatch_semaphore_create(1);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(queue, ^{
while(1){
dispatch_semaphore_wait(source2, DISPATCH_TIME_FOREVER);
if(i == array.count){
// 最后要释放所有信号量,否则会报"EXC_BAD_INSTRUCTION"错误
dispatch_semaphore_signal(source1);
dispatch_semaphore_signal(source2);
break;
}
NSLog(@"%@ %@", [array objectAtIndex:i], [NSThread currentThread]);
i += 1;
dispatch_semaphore_signal(source1);
}
});
dispatch_async(queue, ^{
while(1){
dispatch_semaphore_wait(source1, DISPATCH_TIME_FOREVER);
if(i == array.count){
dispatch_semaphore_signal(source1);
dispatch_semaphore_signal(source2);
break;
}
NSLog(@"%@ %@", [array objectAtIndex:i], [NSThread currentThread]);
i += 1;
dispatch_semaphore_signal(source2);
}
});
}
运行结果如下:
信号量总结:
- 创建信号量:dispatch_semaphore_t sem = dispatch_semaphore_create(初始信号值);
- P操作:dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
- V操作:dispatch_semaphore_signal(sem);
队列总结:
- 拿到主队列(串行):dispatch_queue_t queue = dispatch_get_main_queue();
- 拿到全局队列(并行):dispatch_queue_t queue = dispatch_get_global_queue(优点度, 0);
全局队列优先度总结:
- DISPATCH_QUEUE_PRIORITY_HIGH 2 高
- DISPATCH_QUEUE_PRIORITY_DEFAULT 0 默认
- DISPATCH_QUEUE_PRIORITY_LOW -2 低
- DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN 2 后台优先级