记录一个可能会遇到的应用场景
当前有a,b,c,d,e,f六个任务,要求:
- a,b,c并发执行
- d依赖a,b
- e依赖b,c
- f依赖d,e
这里分别用GCD和NSOperation实现
GCD
func Test_GCD() {
let g1 = DispatchGroup()
let g2 = DispatchGroup()
let g3 = DispatchGroup()
g1.enter()
DispatchQueue.global().async {
for _ in 0..<3{
print("a")
}
g1.leave()
}
g1.enter()
g2.enter()
DispatchQueue.global().async {
for _ in 0..<3{
print("b")
}
g1.leave()
g2.leave()
}
g2.enter()
DispatchQueue.global().async {
for _ in 0..<3{
print("c")
}
g2.leave()
}
g3.enter()
g1.notify(queue: DispatchQueue.global()) {
for _ in 0..<3{
print("d")
}
g3.leave()
}
g3.enter()
g2.notify(queue: DispatchQueue.global()) {
for _ in 0..<3{
print("e")
}
g3.leave()
}
g3.notify(queue: DispatchQueue.global()) {
for _ in 0..<3{
print("f")
}
}
}
NSOperation
func Test_Operation(){
let op1 = BlockOperation.init {
for _ in 0..<3{
print("a")
}
}
let op2 = BlockOperation.init {
for _ in 0..<3{
print("b")
}
}
let op3 = BlockOperation.init {
for _ in 0..<3{
print("c")
}
}
let op4 = BlockOperation.init {
for _ in 0..<3{
print("d")
}
}
let op5 = BlockOperation.init {
for _ in 0..<3{
print("e")
}
}
let op6 = BlockOperation.init {
for _ in 0..<3{
print("f")
}
}
op4.addDependency(op1)
op4.addDependency(op2)
op5.addDependency(op2)
op5.addDependency(op3)
op6.addDependency(op4)
op6.addDependency(op5)
let myQueue = OperationQueue.init()
myQueue.maxConcurrentOperationCount = 6
myQueue.addOperation(op1)
myQueue.addOperation(op2)
myQueue.addOperation(op3)
myQueue.addOperation(op4)
myQueue.addOperation(op5)
myQueue.addOperation(op6)
}