1. GCD
同步/异步和串行/并发
dispatch_sync(serial_queue, ^{// 任务});
dispatch_async(serial_queue, ^{// 任务});
dispatch_sync(concurrent_queue, ^{// 任务});
dispatch_async(concurrent_queue, ^{// 任务});
同步串行
1 | // 死锁: 原因, 队列引起的循环等待, (viewDidLoad和队列Block相互等待) |
同步并发
1 | { |
异步并发
1 | { |
dispatch_barrier_async()
1 | // 多读单写操作 |
dispatch_group_async()
场景: 先并发A, B, C任务, 再执行D
1 | dispatch_group_async(group, concurrent_queue, ^ {// 任务A }); |
2. NSOperation
特点
- 添加任务依赖
- 任务执行状态控制
- 最大并发量
任务执行状态控制
isReady
// 是否就绪isExecuting
// 是否执行isFinished
// 是否完成isCancelled
// 是否已取消
如果只重新main方法, 底层控制变更任务执行完成状态, 以及任务退出.
如果重写了start方法, 自行控制任务状态.
注意: 系统通过KVO的方式 移除一个isFinished=YES
的NSOperation的.
3. NSThread
启动流程
start() -> pthread -> main() -> [target performSelector:sel] -> exit()/ Runloop
4. 锁
哪些锁
- NSRecursivelLock
- @synchronized
@synchronized
一般在创建单例对象的时候使用
atomic
- 修饰属性的关键字
- 对被修饰对象进行原子操作(不负责使用)
1 | @property (atomic) NSMutableArray *array; |
OSSpinLock
- 循环等待询问, 不释放当前资源.
- 用于轻量级数据访问, 简单的int值 +1/ -1操作.
NSLock
1 | { |
案例:
1 | // 死锁 |
NSRecursiveLock
1 | // 使用递归锁解决上述死锁问题 |
dispatch_semaphore
1 | // dispatch_semaphore_t相关函数 |
几个方法的内部实现
1 | // dispatch_semaphore_create(1); |
总结
GCD实现多读单写
Dispatch_barrier_async()
的使用
系统提供了哪几种多线程技术, 各自特点
GCD, NSOPeration, NSThread
NSOperation对象在isFinished
之后是怎样从queue当中移除的?
KVO
用过哪些锁, 结合实际谈谈怎样使用?
NSLock -> NSRecursiveLock
- 本文作者: 醉疏狂
- 本文链接: https://hubin97.github.io/2020/05/20/多线程/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!