GCD

2018-12-28  本文已影响0人  孙凯iOS

GCD

- (void)syncConcurrentGlobal
{
    //同步-并行
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //long identifier 优先级2 0 -2(一般为0)  unsigned long flags作为保留字段备用(一般为0)
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-并发-第一个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-并发-第二个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-并发-第三个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    //同步-并行 不会开启新的线程,并发队列失去了并发的功能
}

- (void)syncSerialCreate
{
    //同步-串行
    dispatch_queue_t queue = dispatch_queue_create("name", NULL);
    //第一个参数是队列名字“”
    //第二个参数是队列类型  NULL是串行  DISPATCH_QUEUE_CONCURRENT是并行
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-串行-第一个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-串行-第二个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"同步-串行-第三个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    //同步-串行 不会开启新的线程
}

- (void)asyncSerialCreate
{
    //异步-串行
    dispatch_queue_t queue = dispatch_queue_create("name", NULL);
    //第一个参数是队列名字“”
    //第二个参数是队列类型  NULL是串行  DISPATCH_QUEUE_CONCURRENT是并行
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-串行-第一个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-串行-第二个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-串行-第三个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    //异步-串行 会开启线程,但是只开启一个线程
}

- (void)asyncConcurrentGlobal
{
    //异步-并行
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //long identifier 优先级2 0 -2(一般为0)  unsigned long flags作为保留字段备用(一般为0)
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-并发-第一个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-并发-第二个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 5; i++) {
            NSLog(@"异步-并发-第三个   %ld-%@",i,[NSThread currentThread]);
        }
    });
    //异步-并发 同时开启三个子线程
}
上一篇下一篇

猜你喜欢

热点阅读