NSArray *array = [[NSArray alloc]initWithObjects:@(1), @(1), @(1), @(1), @(1), nil]; //创建一个信号源 __block dispatch_semaphore_t sem = dispatch_semaphore_create(0); dispatch_queue_t queue = dispatch_queue_create("StudyBlocks", NULL); dispatch_async(queue, ^(void) { int sum = 0; for(int i = 0; i < array.count; i++) sum += (int)array[i]; NSLog(@" >> Sum: %d", sum); //增加 semaphore 计数(可理解为资源数) dispatch_semaphore_signal(sem); }); //减少 semaphore 的计数,如果资源数少于 0就等待资源有资源了再去处理 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); dispatch_release(sem); dispatch_release(queue);
NSArray *array = [[NSArray alloc]initWithObjects:@(1), @(1), @(1), @(1), @(1), nil]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); __block int sum = 0; //dispatch_apply 的定义如下: //dispatch_apply(size_t iterations, dispatch_queue_t queue, void (^block)(size_t)); //参数 iterations 表示迭代的次数,void (^block)(size_t) 是 block 循环体。这么做与 for 循环相比有什么好处呢?答案是:并行,这里的求和是并行的,并不是按照顺序依次执行求和的。 dispatch_apply(array.count, queue, ^(size_t i) { sum += (int)array[i]; }); NSLog(@" >> sum: %d", sum); dispatch_release(queue);
GCD-semaphore(资源)-apply,布布扣,bubuko.com
原文:http://blog.csdn.net/fucheng56/article/details/24372247