互斥锁 自旋锁 递归锁 条件锁 读写锁
- 互斥锁:pthread_ mutex_t(NSLock基于此封装)每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问对象
objc_sync_enter(self)
执行的代码
objc_sync_exit(self)
类似OC的
@synchronized(self) {
执行的代码
}
自旋锁:os_ unfair_ lock_lock(不会陷入死锁) 等待的过程中是一种whiledo的模式,但对象解锁后能最快的拿到对象,称为效率最高的锁
递归锁:NSRecursiveLock 在循环或者递归调用lock时,由于未unlock会导致死锁,此时使用递归,在unlock时会一层层解套(记录递归或者循环的层数让后解)
条件锁:NSConditionLock,可自定义条件,但满足条件时进入lock
let conLock = NSConditionLock.init(condition: 0)
let queue = DispatchQueue.global()
// -------------------- 线程1 --------------------
queue.async {
if conLock.tryLock(whenCondition: 0) {
debugPrint(Thread.current,1)
conLock.unlock(withCondition: 1)
}else{
debugPrint("log1失败")
}
}
// -------------------- 线程2 --------------------
queue.async {
conLock.lock(whenCondition: 3)
debugPrint(Thread.current,2)
conLock.unlock(withCondition: 2)
}
// -------------------- 线程3 --------------------
queue.async {
conLock.lock(whenCondition: 1)
debugPrint(Thread.current,3)
conLock.unlock(withCondition: 3)
}
/// 另外一种方式
let lock = NSConditionLock()
let queue = DispatchQueue.global()
queue.async {
for item in 0...3 {
lock.lock()
debugPrint(Thread.current,item)
sleep(1)
lock.unlock(withCondition: item)
}
}
queue.async {
lock.lock(whenCondition: 2)
debugPrint(Thread.current)
lock.unlock()
}
- 读写锁:可满足多线程读,写的时候唯一线程所有读的线程也许等待
// 读写锁 pthread_rwlock
func lock5() {
let queue = DispatchQueue.global()
for _ in 0..<5 {
queue.async { [weak self] in
self?.readPthreadRWLock()
self?.writePthreadRWLock()
}
}
}
@objc func readPthreadRWLock() {
pthread_rwlock_rdlock(&self.rwLock)
debugPrint(Thread.current,"读文件")
pthread_rwlock_unlock(&self.rwLock)
}
@objc func writePthreadRWLock() {
pthread_rwlock_wrlock(&self.rwLock)
debugPrint(Thread.current,"写文件")
sleep(1)
pthread_rwlock_unlock(&self.rwLock)
}
atomic为何不能完全保证线程安全
atomic是对属性的set/get方法加锁了,保证了读写的线程安全。但并不能保证属性的线程安全,属性还会有其他的操作(加减、添加、移除等)