信号量处理事件并发 用来控制资源被多任务访问的情况 亲测有效
let semaphore = DispatchSemaphore(value: 1) 初始化信号量为1
semaphore.wait() 信号量-1 当前信号量为0 所有操作处于等待状态 不再执行
semaphore.wait() 信号量+1 当前信号量为1 所有操作处于可执行状态 开始执行
let queue = DispatchQueue.global()
let group = DispatchGroup()
let semaphore = DispatchSemaphore(value: 1)
queue.async(group: group) {
semaphore.wait()
self.semaphoreTask(label: "1", cost: 2, complete: {
semaphore.signal()
})
}
queue.async(group: group) {
semaphore.wait()
self.semaphoreTask(label: "2", cost: 2, complete: {
semaphore.signal()
})
}
queue.async(group: group) {
semaphore.wait()
self.semaphoreTask(label: "3", cost: 2, complete: {
semaphore.signal()
})
}
group.notify(queue: queue) {
print("All task has finished")
}
延迟方法
public func semaphoreTask(label:String, cost:UInt32, complete:@escaping ()->()){
print("Start semaphore task \(label)")
sleep(cost)
print("End semaphore task \(label)")
complete()
}
日志输出
Start semaphore task 1
End semaphore task 1
Start semaphore task 2
End semaphore task 2
Start semaphore task 3
End semaphore task 3
All task has finished
网友评论