多线程概念及原理
1.(单核CPU) 同一时间, CPU只能处理1个线程,只有一个线程在执行
2.多线程”同时”执行, 是CPU快速的在多个线程之间的切换
3.CPU调度线程的时间足够快,就造成了多线程的”同时”执行
4.如果线程数非常多,CPU会在n个线程之间切换,消耗大量的CPU资源
延伸知识点: 循环
1.循环的速度是非常快的
2.操作内存的栈空间,速度非常快 // NSString *str = @“Hello”; 存储在常量区
3.操作内存的堆空间,速度有点慢 // alloc
4.循环非常消耗CPU资源
5.I/O操作 速度非常慢
多线程优缺点
优点:
1.能适当提高程序的执行效率
2.能适当提高资源的利用率
3.线程上的任务执行完成后,线程会自动销毁
缺点:
1.开启线程需要占用一定的内存空间(默认情况下,每个线程占用512KB)
2.如果开启大量的线程,会占用大量的内存空间,降低程序的性能
3.线程越多,CPU在调用线程上的开销就越大
4.程序设计更加复杂,比如线程间的通信,多线程共享(例如:多线程在同一时刻修改某个数值)
多线程技术方案
互斥锁和自旋锁
区别:
互斥锁:如果发现其他线程正在执行锁定的代码,线程会进入休眠(就绪状态),等待其他线程时间片到打开锁后,线程会被唤醒(执行)
自旋锁:如果发现有其他线程正在锁定代码,线程会用死循环的方式,一直等待锁定的代码执行完成,自旋锁更适合执行不耗时的代码
- 原子属性内部有一把自旋锁
- 原子属性不能保证同时读写的操作安全性
- 故而原子属性不能解决卖票的共享资源抢占问题
- 需要用到互斥锁,把读和写的操作包装成一个原子块
延伸知识点: GCD信号量:
定义:
信号量就是一种可用来控制访问资源的数量的标识,设定了一个信号量,在线程访问之前,加上信号量的处理,则可告知系统按照我们指定的信号量数量来执行多个线程。
其实,这有点类似锁机制了,只不过信号量都是系统帮助我们处理了,我们只需要在执行线程之前,设定一个信号量值,并且在使用时,加上信号量处理方法就行了。
注意,正常的使用顺序是先降低然后再提高,这两个函数通常成对使用。
核心方法如下:
1 | // 创建信号量,参数:信号量的初值,如果小于0则会返回NULL |
参考:
iOS GCD中级篇 - dispatch_semaphore(信号量)的理解及使用
线程安全
线程同时操作是不安全的,多个线程同时操作同一个全局变量
在多个线程进行读写操作时,仍然能保证数据的正确,线程才是安全的
几乎所有UIKit提供的类都是线程不安全的,所以更新UI操作需要放在主线程
1 | 线程间通信(从子线程回到主线程) |
- 本文作者: 醉疏狂
- 本文链接: https://hubin97.github.io/2020/04/16/多线程总结/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!