GCD的几种使用方法

2020-06-12  本文已影响0人  小白也疯狂

1.栅栏方法:

- (void)queue1 {
    dispatch_queue_t queue = dispatch_queue_create("aaaaaa", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1]; NSLog(@"1---%@",[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; ++i) {
            [NSThread sleepForTimeInterval:1]; NSLog(@"2---%@",[NSThread currentThread]);
        }
    });
    //dispatch_barrier_async
    dispatch_barrier_async(queue, ^{
        for (int i = 0; i < 4; ++i) {
            [NSThread sleepForTimeInterval:1]; NSLog(@"3---%@",[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 3; ++i) {
            [NSThread sleepForTimeInterval:1]; NSLog(@"4---%@",[NSThread currentThread]);
        }
    });
}

2.快速迭代

- (void)queue2 {
    dispatch_queue_t queue = dispatch_queue_create("bbbbbb", DISPATCH_QUEUE_CONCURRENT);
    //dispatch_apply
    dispatch_apply(5, queue, ^(size_t index) {
        NSLog(@"-----%ld----%@",index,[NSThread currentThread]);
    });
    NSLog(@"完成");
}

3.信号量

@property (nonatomic, assign) NSInteger number;
@property (nonatomic, strong) dispatch_semaphore_t semp;

- (void)queue3 {
    self.number = 50;
    dispatch_queue_t queue1 = dispatch_queue_create("cccccc", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue2 = dispatch_queue_create("dddddd", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue3 = dispatch_queue_create("eeeeee", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue4 = dispatch_queue_create("ffffff", DISPATCH_QUEUE_SERIAL);
    //创建
    self.semp = dispatch_semaphore_create(1);
    __weak typeof(self)wekeSelf = self;
    dispatch_async(queue1, ^{
        [wekeSelf queue4];
    });
    dispatch_async(queue2, ^{
        [wekeSelf queue4];
    });
    dispatch_async(queue3, ^{
        [wekeSelf queue4];
    });
    dispatch_async(queue4, ^{
        [wekeSelf queue4];
    });
}
- (void)queue4 {
    while (1) {
        //-1
        dispatch_semaphore_wait(self.semp, DISPATCH_TIME_FOREVER);
        if (self.number > 0) {
            NSLog(@"----%ld----%@",self.number,[NSThread currentThread]);
            self.number --;
        } else {
            NSLog(@"完成");
            break;
        }
        //+1
        dispatch_semaphore_signal(self.semp);
    };
}
上一篇 下一篇

猜你喜欢

热点阅读