iOS多任务并发设计

原文
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");
    });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值