iOS 线程简述

一、 串行队列和并行队列

我们先看一下队列的概念。

队列是先进先出(FIFO)结构的,其主要的任务主要是负责线程的创建、回收工作,不论什么队列和什么任务都不需要程序员参与,减轻了程序员的工作。

队列主要分为:

  1. GCD队列
  • 运行在主线程中的主队列。
  • 3 个不同优先级的后台队列(全局队列)。
  • 一个优先级更低的后台队列(用于 I/O,全局队列property=background)。
  1. 自定义队列
  • 串行队列
  • 并行队列。
    自定义队列非常强大,建议在开发中使用。在自定义队列中被调度的所有Block最终都将被放入到系统的全局队列中和线程池中。

下面看一张非常重要的图。


img01

摘抄自https://www.jianshu.com/p/cc875ef54aa9

二、队列和执行方式的随机组合

执行方式有同步执行sync和异步执行 async两种
自定义队列有串行队列serial和并行队列concurrent加上系统的主队列mainQueue和全局队列globalQueue,共四种

那么两种执行方式和四种队列共有8种组合,分别为:

1. 串行队列+异步执行
//串行队列+异步执行
-(void)serialAndAsync{
    
    NSLog(@"当前线程--%@",[NSThread currentThread]);
    //第二个参数传NULL或者0也表示串行队列
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
    for (int i=0; i<5; i++) {
        
        void(^task)(void) = ^{
            NSLog(@"%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queue, task);
    }
    
}
当前线程--<NSThread: 0x6000026b0240>{number = 1, name = main}
0--<NSThread: 0x600002dc4000>{number = 5, name = (null)}
1--<NSThread: 0x600002dc4000>{number = 5, name = (null)}
2--<NSThread: 0x600002dc4000>{number = 5, name = (null)}
3--<NSThread: 0x600002dc4000>{number = 5, name = (null)}
4--<NSThread: 0x600002dc4000>{number = 5, name = (null)}

结合执行结果示例可知

  • 开辟了新线程
  • 任务是串行执行的
2. 串行队列+同步执行
//串行队列+同步执行
-(void)serialAndSync{
   NSLog(@"当前线程%@",[NSThread currentThread]);
   dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
   for (int i=0; i<5; i++) {
       void(^task)(void) = ^{
           NSLog(@"%d--%@",i,[NSThread currentThread]);
       };
       dispatch_sync(queue, task);
   }
}
当前线程<NSThread: 0x600001fa8e80>{number = 1, name = main}
0--<NSThread: 0x600001fa8e80>{number = 1, name = main}
1--<NSThread: 0x600001fa8e80>{number = 1, name = main}
2--<NSThread: 0x600001fa8e80>{number = 1, name = main}
3--<NSThread: 0x600001fa8e80>{number = 1, name = main}
4--<NSThread: 0x600001fa8e80>{number = 1, name = main}

结合执行结果示例可知

  • 任务在主线程执行
  • 任务是串行执行的
3. 并行队列+同步执行
//并行队列+异步执行
-(void)concurrentAndAsync{
   dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
   for (int i=0; i<5; i++) {
       void(^task)(void) = ^{
           NSLog(@"%d--%@",i,[NSThread currentThread]);
       };
       dispatch_async(queue, task);
   }
}
当前线程<NSThread: 0x600003044f00>{number = 1, name = main}
4--<NSThread: 0x60000304f8c0>{number = 3, name = (null)}
2--<NSThread: 0x60000304d540>{number = 6, name = (null)}
0--<NSThread: 0x600003064540>{number = 7, name = (null)}
1--<NSThread: 0x600003010800>{number = 5, name = (null)}
3--<NSThread: 0x600003064f80>{number = 4, name = (null)}

结合执行结果示例可知

  • 开辟了多条子线程
  • 任务是并行执行的

⚠️注:当我们没有对子线程数量做限制时系统并不会无限量创建子线程

4. 并行队列+同步执行
//并行队列+同步执行
-(void)concurrentAndSync{
   NSLog(@"当前线程%@",[NSThread currentThread]);
   dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
   for (int i=0; i<5; i++) {
       void(^task)(void) = ^{
           NSLog(@"%d--%@",i,[NSThread currentThread]);
       };
       dispatch_sync(queue, task);
   }
}
当前线程<NSThread: 0x6000020b85c0>{number = 1, name = main}
0--<NSThread: 0x6000020b85c0>{number = 1, name = main}
1--<NSThread: 0x6000020b85c0>{number = 1, name = main}
2--<NSThread: 0x6000020b85c0>{number = 1, name = main}
3--<NSThread: 0x6000020b85c0>{number = 1, name = main}
4--<NSThread: 0x6000020b85c0>{number = 1, name = main}

结合执行结果示例可知

  • 运行在主线程
  • 任务是串行执行的
5. 主队列+同步执行
//主队列+同步执行
-(void)mainQueueAndSync{
    NSLog(@"当前线程%@",[NSThread currentThread]);
    dispatch_queue_t queue = dispatch_get_main_queue();
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"%d--%@",i,[NSThread currentThread]);
        };
        dispatch_sync(queue, task);
    }
}

崩溃了

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

分析原因:

  • 主队列的任务一定会在主线程执行
  • 同步执行dispatch_sync本身也是一个任务

那么对于主线程来说接收了6个任务:

  1. mainQueueAndSync任务
  2. 任务1
  3. 任务2
  4. 任务3
  5. 任务4
  6. 任务5

对主线程来说先要完成mainQueueAndSync任务才会去执行下一个任务,也就是任务1,但是mainQueueAndSync任务执行完成的前提是任务1到任务5都执行完毕,所以就出现了线程等待,一直等到死...

如何破解线程死锁,那就是将mainQueueAndSync任务放到子线程去执行

//主队列+同步执行
-(void)mainQueueAndSync{
    NSLog(@"当前线程%@",[NSThread currentThread]);
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"%d--%@",i,[NSThread currentThread]);
        };
        [NSThread detachNewThreadWithBlock:^{
            dispatch_sync(queue, task);
        }];
    }
}
当前线程<NSThread: 0x600000784280>{number = 1, name = main}
0--<NSThread: 0x600000784280>{number = 1, name = main}
1--<NSThread: 0x600000784280>{number = 1, name = main}
2--<NSThread: 0x600000784280>{number = 1, name = main}
3--<NSThread: 0x600000784280>{number = 1, name = main}
4--<NSThread: 0x600000784280>{number = 1, name = main}
6. 主队列+异步执行
//主队列+异步执行
-(void)mainQueueAndAsync{
    NSLog(@"当前线程%@",[NSThread currentThread]);
    dispatch_queue_t queue = dispatch_get_main_queue();
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queue, task);
    }
}
当前线程<NSThread: 0x60000396cec0>{number = 1, name = main}
0--<NSThread: 0x60000396cec0>{number = 1, name = main}
1--<NSThread: 0x60000396cec0>{number = 1, name = main}
2--<NSThread: 0x60000396cec0>{number = 1, name = main}
3--<NSThread: 0x60000396cec0>{number = 1, name = main}
4--<NSThread: 0x60000396cec0>{number = 1, name = main}

结合执行结果示例可知

  • 运行在主线程
  • 任务是串行执行的
7. 全局队列+异步执行
//全局队列+异步执行
-(void)globalQueueAndAsync{
   NSLog(@"当前线程%@",[NSThread currentThread]);
   dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
   for (int i=0; i<5; i++) {
       void(^task)(void) = ^{
           NSLog(@"%d--%@",i,[NSThread currentThread]);
       };
       dispatch_async(queue, task);
   }
}
当前线程<NSThread: 0x60000068cf00>{number = 1, name = main}
0--<NSThread: 0x6000006dc200>{number = 5, name = (null)}
3--<NSThread: 0x60000069cec0>{number = 7, name = (null)}
2--<NSThread: 0x6000006de500>{number = 6, name = (null)}
1--<NSThread: 0x6000006ca400>{number = 4, name = (null)}
4--<NSThread: 0x6000006dc7c0>{number = 8, name = (null)}

结果同并行队列+异步执行一样,全局队列本身就是一个并行队列

8. 全局队列+同步执行
//全局队列+同步执行
-(void)globalQueueAndSync{
   NSLog(@"当前线程%@",[NSThread currentThread]);
   dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
   for (int i=0; i<5; i++) {
       void(^task)(void) = ^{
           NSLog(@"%d--%@",i,[NSThread currentThread]);
       };
       dispatch_sync(queue, task);
   };
   
}
当前线程<NSThread: 0x600002b98100>{number = 1, name = main}
0--<NSThread: 0x600002b98100>{number = 1, name = main}
1--<NSThread: 0x600002b98100>{number = 1, name = main}
2--<NSThread: 0x600002b98100>{number = 1, name = main}
3--<NSThread: 0x600002b98100>{number = 1, name = main}
4--<NSThread: 0x600002b98100>{number = 1, name = main}

结果同并行队列+同步执行一样

img02

三、 全局队列的优先级

/*!
 * @typedef dispatch_queue_priority_t
 * Type of dispatch_queue_priority
 *
 * @constant DISPATCH_QUEUE_PRIORITY_HIGH
 * Items dispatched to the queue will run at high priority,
 * i.e. the queue will be scheduled for execution before
 * any default priority or low priority queue.
 *
 * @constant DISPATCH_QUEUE_PRIORITY_DEFAULT
 * Items dispatched to the queue will run at the default
 * priority, i.e. the queue will be scheduled for execution
 * after all high priority queues have been scheduled, but
 * before any low priority queues have been scheduled.
 *
 * @constant DISPATCH_QUEUE_PRIORITY_LOW
 * Items dispatched to the queue will run at low priority,
 * i.e. the queue will be scheduled for execution after all
 * default priority and high priority queues have been
 * scheduled.
 *
 * @constant DISPATCH_QUEUE_PRIORITY_BACKGROUND
 * Items dispatched to the queue will run at background priority, i.e. the queue
 * will be scheduled for execution after all higher priority queues have been
 * scheduled and the system will run items on this queue on a thread with
 * background status as per setpriority(2) (i.e. disk I/O is throttled and the
 * thread's scheduling priority is set to lowest value).
 */
#define DISPATCH_QUEUE_PRIORITY_HIGH 2
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN

备注信息可以看到全局队列默认设置4种优先级,CPU按照优先级由高到低的顺序依次执行

//全局队列+同步执行之不同优先级
-(void)globalQueueAndSync{
    NSLog(@"当前线程%@",[NSThread currentThread]);
    dispatch_queue_t queueBackground =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    dispatch_queue_t queueLow =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_queue_t queueDefault =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t queueHigh =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"BACKGROUND%d--%@",i,[NSThread currentThread]);
        };
        dispatch_sync(queueBackground, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"LOW%d--%@",i,[NSThread currentThread]);
        };
        dispatch_sync(queueLow, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"DEFAULT%d--%@",i,[NSThread currentThread]);
        };
        dispatch_sync(queueDefault, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"HIGH%d--%@",i,[NSThread currentThread]);
        };
        dispatch_sync(queueHigh, task);
    };
    
}
当前线程<NSThread: 0x600002f6cd40>{number = 1, name = main}
BACKGROUND0--<NSThread: 0x600002f6cd40>{number = 1, name = main}
BACKGROUND1--<NSThread: 0x600002f6cd40>{number = 1, name = main}
BACKGROUND2--<NSThread: 0x600002f6cd40>{number = 1, name = main}
BACKGROUND3--<NSThread: 0x600002f6cd40>{number = 1, name = main}
BACKGROUND4--<NSThread: 0x600002f6cd40>{number = 1, name = main}
LOW0--<NSThread: 0x600002f6cd40>{number = 1, name = main}
LOW1--<NSThread: 0x600002f6cd40>{number = 1, name = main}
LOW2--<NSThread: 0x600002f6cd40>{number = 1, name = main}
LOW3--<NSThread: 0x600002f6cd40>{number = 1, name = main}
LOW4--<NSThread: 0x600002f6cd40>{number = 1, name = main}
DEFAULT0--<NSThread: 0x600002f6cd40>{number = 1, name = main}
DEFAULT1--<NSThread: 0x600002f6cd40>{number = 1, name = main}
DEFAULT2--<NSThread: 0x600002f6cd40>{number = 1, name = main}
DEFAULT3--<NSThread: 0x600002f6cd40>{number = 1, name = main}
DEFAULT4--<NSThread: 0x600002f6cd40>{number = 1, name = main}
HIGH0--<NSThread: 0x600002f6cd40>{number = 1, name = main}
HIGH1--<NSThread: 0x600002f6cd40>{number = 1, name = main}
HIGH2--<NSThread: 0x600002f6cd40>{number = 1, name = main}
HIGH3--<NSThread: 0x600002f6cd40>{number = 1, name = main}
HIGH4--<NSThread: 0x600002f6cd40>{number = 1, name = main}

同步执行严格按照FIFO顺序执行全局队列中的任务,这个时候优先级并没有起作用

//全局队列+异步执行之不同优先级
-(void)globalQueueAndSync{
    NSLog(@"当前线程%@",[NSThread currentThread]);
    dispatch_queue_t queueBackground =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    dispatch_queue_t queueLow =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_queue_t queueDefault =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t queueHigh =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"BACKGROUND%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueBackground, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"LOW%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueLow, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"DEFAULT%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueDefault, task);
    };
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"HIGH%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueHigh, task);
    };
    
}

这个我猜测执行结果应该按照high-default-low-background的顺序依此执行,但是事实并不是这样

当前线程<NSThread: 0x600000a00500>{number = 1, name = main}
DEFAULT1--<NSThread: 0x600000a14780>{number = 4, name = (null)}
DEFAULT3--<NSThread: 0x600000a1b5c0>{number = 7, name = (null)}
DEFAULT2--<NSThread: 0x600000a511c0>{number = 6, name = (null)}
DEFAULT4--<NSThread: 0x600000a4f800>{number = 8, name = (null)}
DEFAULT0--<NSThread: 0x600000a24680>{number = 5, name = (null)}
HIGH0--<NSThread: 0x600000a14980>{number = 3, name = (null)}
HIGH1--<NSThread: 0x600000a4eb40>{number = 9, name = (null)}
HIGH2--<NSThread: 0x600000a50140>{number = 10, name = (null)}
HIGH4--<NSThread: 0x600000a1b5c0>{number = 7, name = (null)}
HIGH3--<NSThread: 0x600000a4ed80>{number = 11, name = (null)}
LOW0--<NSThread: 0x600000a511c0>{number = 6, name = (null)}
LOW1--<NSThread: 0x600000a085c0>{number = 12, name = (null)}
LOW3--<NSThread: 0x600000a14980>{number = 3, name = (null)}
LOW4--<NSThread: 0x600000a24680>{number = 5, name = (null)}
LOW2--<NSThread: 0x600000a4eb40>{number = 9, name = (null)}
BACKGROUND2--<NSThread: 0x600000a50140>{number = 10, name = (null)}
BACKGROUND0--<NSThread: 0x600000a4f800>{number = 8, name = (null)}
BACKGROUND1--<NSThread: 0x600000a14780>{number = 4, name = (null)}
BACKGROUND3--<NSThread: 0x600000a1b500>{number = 13, name = (null)}
BACKGROUND4--<NSThread: 0x600000a25bc0>{number = 14, name = (null)}

将default和high优先级队列执行顺序调换之后,打印结果也跟着改变了

...
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"HIGH%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueHigh, task);
    };
    
    for (int i=0; i<5; i++) {
        void(^task)(void) = ^{
            NSLog(@"DEFAULT%d--%@",i,[NSThread currentThread]);
        };
        dispatch_async(queueDefault, task);
    };
...
HIGH1--<NSThread: 0x6000015a59c0>{number = 4, name = (null)}
HIGH2--<NSThread: 0x6000015d8940>{number = 5, name = (null)}
HIGH0--<NSThread: 0x6000015a5040>{number = 3, name = (null)}
HIGH3--<NSThread: 0x6000015d6040>{number = 6, name = (null)}
HIGH4--<NSThread: 0x6000015c1c00>{number = 7, name = (null)}
DEFAULT1--<NSThread: 0x6000015d8700>{number = 9, name = (null)}
DEFAULT0--<NSThread: 0x6000015d6140>{number = 8, name = (null)}
DEFAULT3--<NSThread: 0x6000015a59c0>{number = 4, name = (null)}
DEFAULT2--<NSThread: 0x6000015dd1c0>{number = 10, name = (null)}
DEFAULT4--<NSThread: 0x6000015d8940>{number = 5, name = (null)}

似乎high并没有比defaut优先级高,而是跟执行顺序又关系。
为什么?????
有大佬知道其中原委还望告知🙏

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容