1.GCD控制线程数量
- (void)gcd_max_queue
{
dispatch_queue_t taskConcurrentQueue = dispatch_queue_create("com.task", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t serialQueue = dispatch_queue_create("com.serial", DISPATCH_QUEUE_SERIAL);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(4);
for(NSIntegeri =0; i <10; i++) {
dispatch_async(serialQueue, ^{ dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
dispatch_async(taskConcurrentQueue, ^{
NSLog(@"开始执行任务 %@", [NSThreadcurrentThread]);
sleep(i%4);
NSLog(@"执行任务结束 %@", [NSThreadcurrentThread]);
dispatch_semaphore_signal(semaphore);
});
});
}
}
2.GCD控制线程数量+线程任务结束通知处理
- (void)gcd_max_queue2
{
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for(NSIntegeri =0; i <20; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_group_async(group, queue, ^{
NSLog(@"开始执行任务 %@", [NSThreadcurrentThread]);
sleep(i%4);
NSLog(@"执行任务结束 %@", [NSThreadcurrentThread]);
dispatch_semaphore_signal(semaphore);
});
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"总任务结束!!! %@", [NSThreadcurrentThread]);
});
}
网友评论