Multithreading in Swift

  • Thread

  • Cocoa Operation (Operation and OperationQueue)

    • object-oriented
    • Cancel, dependency, task priority, complex logic, save business state, subclass
  • Grand Central Dispath (GCD)

Thread

  • lightweight

  • You need to manage the thread’s declaration cycle and thread synchronization yourself

Shortcut Creation

  • detachNewThread(_ block: @escaping() -> void)
    • Enter an escape closure that can be executed later
  • detachNewThreadSelector(_ selector: Selector, toTarget target: Any, with argument: Any? )

The initializer

  • Thread(target:, selector:, object:)
  • Need to manuallystartthread
for i in 0..<10 {
    Thread.detachNewThread {
        print(i)
    }
}

class ObjectThread {
    func threadTest(a) {
        let thread = Thread(target: self, selector: #selector(threadWorker), object: nil)
        
        thread.start()
    }
    @objc func threadWorker(a) {
        print("threadWorker")}}let obj = ObjectThread()
obj.threadTest()
Copy the code

Operation

  • Operation
    • state
      • isReady, isExecuting, isFinished, isCancelled
    • sysc
      • main()
    • async
      • start() -> isAsynchronous -> isEexcuting -> isFinished
      • AfNetWorking
    • Add and remove dependencies
  • OperationQueue
    • Thread pool to add Opeartion to queue
    • The underlying use of GCD
    • MaxConcurrentOperationCount can set the maximum number of concurrent
    • DefaultMaxConcurrentOperationCount according to the current system condition dynamically determine the maximum number of concurrent
    • All operations can be cancelled, but those currently executing will not be cancelled
    • So when the Operation completes, exit from destruction
  • BlockOperation
        class ObjectOperation {
            func test(a)  {
                let operation = BlockOperation{[weak self] in
                    self?.threadWorker()
                }
    
                let queue = OperationQueue()
                queue.addOperation(operation)
            }
    
            @objc func threadWorker(a) {
                sleep(1)
                print("threadWorker")}}let obj = ObjectOperation()
        obj.test()
        print("after invoke test")
    Copy the code
  • Inheriting the Operation
    class ObjectOperation {
        func test(a)  {
            let operation = MyOperation(a)let queue = OperationQueue()
            queue.addOperation(operation)
        }
    
        @objc func threadWorker(a) {
            sleep(1)
            print("threadWorker")}}class MyOperation: Operation {
        override func main(a) {
            sleep(1)
            print("in MyOperation main")}}let obj = ObjectOperation()
    obj.test()
    print("after invoke test")
    
    Copy the code
  • Operation completed callback
    • completionBlock
    class ObjectOperation {
        func test(a)  {
            let operation = MyOperation()
            operation.completionBlock = { () -> Void in
                print("completionBlock")}let queue = OperationQueue()
            queue.addOperation(operation)
        }
    
        @objc func threadWorker(a) {
            sleep(1)
            print("threadWorker")}}class MyOperation: Operation {
        override func main(a) {
            sleep(1)
            print("in MyOperation main")}}let obj = ObjectOperation()
    obj.test()
    print("after invoke test")
    Copy the code