把一个task加入一个DispatchGroup有两种方式
方式一: 通过enter()和leave()
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "com.1")
let queue2 = DispatchQueue(label: "com.2")
let queue3 = DispatchQueue(label: "com.3")
group.enter()
queue1.async(){
for i in 0...10{
print("i = \(i)",Thread.current)
}
group.leave()
}
group.enter()
queue2.async(){
for j in 11...20{
print("j = \(j)",Thread.current)
}
group.leave()
}
group.enter()
queue3.async(){
for n in 21...30{
print("n = \(n)",Thread.current)
}
group.leave()
}
group.notify(queue: .main){
print("ok")
}
方法二:直接吧task加入到group
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "com.1")
let queue2 = DispatchQueue(label: "com.2")
let queue3 = DispatchQueue(label: "com.3")
queue1.async(group: group){
for i in 0...10{
print("i = \(i)",Thread.current)
}
}
queue2.async(group: group){
for j in 11...20{
print("j = \(j)",Thread.current)
}
}
queue3.async(group: group){
for n in 21...30{
print("n = \(n)",Thread.current)
}
}
group.notify(queue: .main){
print("ok")
}
上面的task全是异步并发执行的,如果想让上面的代码顺序执行怎么办?加入信号量机制即可
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "com.1")
let queue2 = DispatchQueue(label: "com.2")
let queue3 = DispatchQueue(label: "com.3")
let semaphore = DispatchSemaphore(value: 1)
semaphore.wait()
queue1.async(group: group){
for i in 0...10{
print("i = \(i)",Thread.current)
}
group.leave()
}
semaphore.wait()
queue2.async(group: group){
for j in 11...20{
print("j = \(j)",Thread.current)
}
group.leave()
}
semaphore.wait()
queue3.async(group: group){
for n in 21...30{
print("n = \(n)",Thread.current)
}
group.leave()
}
group.notify(queue: .main){
print("ok")
}
semaphore.wait()是先把信号semaphore的值减1,然后在于0比较,如果大于等于0,则执行任务,如果小于0则把任务挂起,当信号量大于等于0的时候在唤醒执行任务。如果还有不理解的,请参考《计算机操作系统》这本书。