GCD基本使用

  • 同步 sync
  • 异步 async
  • 串行 DISPATCH_QUEUE_SERIAL
  • 并行 DISPATCH_QUEUE_CONCURRENT

异步+并行

开启多条子线程,任务异步(非顺序)执行

- (void)asyncConcurrent {
    dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_CONCURRENT);
    for (int index = 0; index < 20; index ++) {
        dispatch_async(queue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

异步+串行

开启一条子线程,任务串行(顺序)执行

- (void)asyncSerial {
    dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_SERIAL);
    for (int index = 0; index < 20; index ++) {
        dispatch_async(queue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

同步 + 并行

不会开线程,任务串行(顺序)执行

- (void)syncConcurrent {
    dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_CONCURRENT);
    for (int index = 0; index < 20; index ++) {
        dispatch_sync(queue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

同步 + 串行

不会开线程,任务串行(顺序)执行

- (void)syncSerial {
    dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_SERIAL);
    for (int index = 0; index < 20; index ++) {
        dispatch_sync(queue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

全局并发队列

- (void)global {
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    for (int index = 0; index < 20; index ++) {
        dispatch_async(queue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

主队列

获取主队列

dispatch_queue_t mainQueue = dispatch_get_main_queue();

主队列 + 异步

不会开线程,所有任务都在主线程中顺序执行

- (void)asyncMain {
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    for (int index = 0; index < 20; index ++) {
        dispatch_async(mainQueue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

主队列 + 同步(crush)

发生死锁现象

- (void)syncMain {
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    for (int index = 0; index < 20; index ++) {
        dispatch_sync(mainQueue, ^{
            NSLog(@"index:%d, currentThread:%@", index, [NSThread currentThread]);
        });
    }
}

线程间通信

dispatch_async(dispatch_get_main_queue(), ^{
    // UI操作
});

你可能感兴趣的:(GCD基本使用)