Multithreading: Operation (2), multithreading operation
1. Operation set dependency
First, let's see how to set operation dependencies.
What is dependency? What's the purpose?
For example, to create a paid App for listening to music, you need to log on, pay, download, and play. As a matter of fact, we can see from a glance that these four operations are sequential, but if all operations are multi-threaded, how can we control the order?
By setting "Priority "? NO! There is no way to do this with priority. (Equivalent to synchronization in the operating system)
We can establish a sequence by setting the dependency. Only when all operation operations on which an operation depends are completed can this operation be executed.
In addition, operation can establish dependencies across queues!
Note that you must first establish the operation dependency and then add it to the queue.
The code is very simple. See:
1 fileprivate func startDepencyDemo() { 2 operationQueue.maxConcurrentOperationCount = 4 3 self.activityIndicator.startAnimating() 4 guard let url = URL(string: "https://placebeard.it/355/140") else {return } 5 let op1 = convenienceOperation(setImageView: imageView1, withURL: url) 6 let op2 = convenienceOperation(setImageView: imageView2, withURL: url) 7 op2.addDependency(op1) 8 let op3 = convenienceOperation(setImageView: imageView3, withURL: url) 9 op3.addDependency(op2)10 let op4 = convenienceOperation(setImageView: imageView4, withURL: url)11 op4.addDependency(op3)12 13 DispatchQueue.global().async {14 [weak self] in15 self?.operationQueue.addOperations([op1,op2,op3,op4], waitUntilFinished: true)16 DispatchQueue.main.async {17 self?.activityIndicator.stopAnimating()18 }19 }20 21 }
View Code