为GCD并发队列设置最大并发数
2024-11-13 本文已影响0人
nick5683
// 创建一个信号量,初始值为3,表示同时最多允许3个任务并发执行
dispatch_semaphore_t semaphore = dispatch_semaphore_create(3);
// 创建一个dispatch group
dispatch_group_t group = dispatch_group_create();
// 创建一个全局并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 添加第一个任务到group
dispatch_group_async(group, queue, ^{
dispatch_group_enter(group);
// 等待信号量,如果信号量为0,则此任务将被阻塞
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 模拟任务执行时间
for (int i = 0; i < 20; ++i) {
[NSThread sleepForTimeInterval:2]; // 模拟耗时操作
NSLog(@"Task 1 --- %@", [NSThread currentThread]); // 打印当前线程
}
// 任务完成后,释放信号量
dispatch_semaphore_signal(semaphore);
// 离开group
dispatch_group_leave(group);
});
// 添加第二个任务到group
dispatch_group_async(group, queue, ^{
dispatch_group_enter(group);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int i = 0; i < 20; ++i) {
[NSThread sleepForTimeInterval:2]; // 模拟耗时操作
NSLog(@"Task 2 --- %@", [NSThread currentThread]); // 打印当前线程
}
dispatch_semaphore_signal(semaphore);
dispatch_group_leave(group);
});
// 添加第三个任务到group
dispatch_group_async(group, queue, ^{
dispatch_group_enter(group);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int i = 0; i < 20; ++i) {
[NSThread sleepForTimeInterval:2]; // 模拟耗时操作
NSLog(@"Task 3 --- %@", [NSThread currentThread]); // 打印当前线程
}
dispatch_semaphore_signal(semaphore);
dispatch_group_leave(group);
});
// 等待所有任务完成
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 所有文件都下载完成,执行这里的代码
NSLog(@"Task 所有文件都下载完成 --- %@", [NSThread currentThread]); // 打印当前线程
});