原文
1、dispatch_group
#define OPERATION_COUNT 10000
#define OPERATION_SLEEP_TIME 0.01f
- (void)myOperation:(NSInteger)index {
[NSThread sleepForTimeInterval:OPERATION_SLEEP_TIME];
}
- (void)runMyOperationsWithGCD {
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < OPERATION_COUNT; i++) {
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
[self myOperation:i];
});
}
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"operations are finished");
});
}
2、NSOperationQueue
#define MAX_CONCURRENT_COUNT 10
#define OPERATION_COUNT 10000
#define OPERATION_SLEEP_TIME 0.1f
- (void)myOperation:(NSInteger)index {
NSLog(@"enter myOperation:%ld, thread:%@", (long)index, [NSThread currentThread]);
[NSThread sleepForTimeInterval:OPERATION_SLEEP_TIME];
}
- (void)runMyOPerationsWithNSOperation {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = MAX_CONCURRENT_COUNT;//设置最大并发数
for (int i = 0; i < OPERATION_COUNT; i++) {
[queue addOperationWithBlock:^{
[self myOperation:i];
}];
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[queue waitUntilAllOperationsAreFinished];//等待所有任务完成
NSLog(@"operations are finished");
});
}
3、信号量
#define MAX_CONCURRENT_COUNT 10
#define OPERATION_COUNT 10000
#define OPERATION_SLEEP_TIME 0.1f
- (void)myOperation:(NSInteger)index {
NSLog(@"enter myOperation:%ld, thread:%@", (long)index, [NSThread currentThread]);
[NSThread sleepForTimeInterval:OPERATION_SLEEP_TIME];
}
- (void)runMyOperationsWithSemaphore {
//创建信号量,控制最大并发数为10
dispatch_semaphore_t semaphore = dispatch_semaphore_create(MAX_CONCURRENT_COUNT);
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < OPERATION_COUNT; i++) {
//wait一次,semaphore减一,当semaphore小于0时会一直wait
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
[self myOperation:i];
//任务完成后,触发semaphore,以允许新的任务进入
dispatch_semaphore_signal(semaphore);
});
}
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"operations are finished");
});
}