iOS多线程最常用是GCD和NSOperation。一般简单的异步任务直接使用GCD,需要控制最大并发数和控制状态时我选择封装NSOperation(SDWebImage和AFN也是封装的NSOperation),NSThread一般和常驻线程使用(如AFN框架)。
NSOperation直接使用系统提供的maxConcurrentOperationCount可设置最大并发数,GCD则需要结合信号量手动去控制。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);
dispatch_async(workConcurrentQueue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"1");
sleep(5);
dispatch_semaphore_signal(semaphore);
});
dispatch_async(workConcurrentQueue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"2");
sleep(3);
dispatch_semaphore_signal(semaphore);
});
dispatch_async(workConcurrentQueue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"3");
dispatch_semaphore_signal(semaphore);
});
dispatch_async(workConcurrentQueue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"4");
dispatch_semaphore_signal(semaphore);
});