GCD基本使用

2019-01-27  本文已影响0人  DPL1024

异步+并行

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

- (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操作
});
上一篇下一篇

猜你喜欢

热点阅读