【学习】重学Swift5-多线程

八、多线程

  1. Thread

    // 最轻量级,但需要自己管理线程的生命周期和线程同步。线程同步对数据的加锁会有一定的系统开销。
    // 简便
    for i in 0...10 {
        Thread.detachNewThread {
            print(i)
        }
    }
    // 初始化器
    class ObjectThread {
        func threadTest() {
            let thread = Thread.init(target: self, selector: #selector(threadWork), object: nil)
            thread.start()
            
            print("start thread")
        }
        
        @objc func threadWork() {
            print("thread work")
        }
    }
    
    let obj = ObjectThread()
    obj.threadTest()
    
  2. Cocoa Operation(Operation和OperationQueue)

    // Operation:Operation、BlockOperation
    // isReady、isExecuting、isFinished、iscancelled
    /*
    1.同步 sync 主要实现main()
    2.异步 async  start() isAsnchronous isExecuting isFinished
    */
    // addDependency removeDependency dependencies
    
    // OperationQueue
    /*
    一个queue可以加入多个Operation
    底层使用GCD
    maxConcurrentOperationCount
    defaultMaxConcurrentOperationCount
    可以取消所有的Operation,但是正在执行的不会取消
    所有的Operation执行完毕后退出销毁
    */
    // demo1
    class ObjectOperation {
        func operationTest() {
    
            let operation = BlockOperation.init { [weak self] in
                self?.operationWork()
            }
    
            let queue = OperationQueue()
            queue.addOperation(operation)
    
            print("operation thread")
        }
    
        @objc func operationWork() {
            sleep(1)
            print("operation work")
        }
    }
    
    let obj = ObjectOperation()
    obj.operationTest()
    print("After test")
    
    // demo2
    
    class ObjectOperation {
        func operationTest() {
            
            let operation = MyOperation()
          // 回调
            operation.completionBlock = { () -> Void in
                print("completionBlock")
            }
            let queue = OperationQueue()
            queue.addOperation(operation)
            print("operation thread")
        }
        
        @objc func operationWork() {
            sleep(1)
            print("operation work")
        }
    }
    
    class MyOperation: Operation {
        override func main() {
            sleep(1)
            print("in opertaion main")
        }
    }
    
    let obj = ObjectOperation()
    obj.operationTest()
    print("After test")
    
    // completionBlock 完成后的回调
    
  3. GCD基本操作

    // 队列
    主队列、并行队列、串行队列
    // sync async asyncAfter
    
    // sync 提交任务到当前队列,并且知道任务执行完成,当前队列才会返回
    // async 调度一个任务去立即执行,但是不用等任务执行完成当前队列就会返回
    // asyncAfter 调度一个任务去多久之后执行,但是不用等任务执行完当前队列就会返回
    
    // 同步
    let queue = DispatchQueue.init(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
    
    queue.sync {
        print("in queue sync")
    }
    print("after queue method")
    
    // 异步
    queue.async {
        sleep(1)
        print("in queue sync")
    }
    
    // asyncAfter
    queue.asyncAfter(deadline: .now()+1) {
        print("asyncAfter")
    };
    
  4. GCD的两个高级操作

    // DispatchGroup
    let workingGroup = DispatchGroup()
    // 串行队列 顺序执行  使用上面queue则是并行队列
    let workingQueue = DispatchQueue(label: "request_queue")
    
    workingGroup.enter()
    workingQueue.async {
        Thread.sleep(forTimeInterval: 1)
        print("接口1 数据请求完成")
        workingGroup.leave()
    }
    
    workingGroup.enter()
    workingQueue.async {
        Thread.sleep(forTimeInterval: 1)
        print("接口2 数据请求完成")
        workingGroup.leave()
    }
    
    print("我是最开始执行的,异步操作里的打印后执行")
    
    workingGroup.wait()
    print("两个接口都请求完毕")
    print("阻塞")
    
    workingGroup.notify(queue: workingQueue) {
        print("两个接口都请求完毕")
    }
    print("不阻塞")
    
    // DispatchSource
    var seconds = 10
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
    timer.schedule(deadline: .now(), repeating: 1.0)
    timer.setEventHandler {
            seconds -= 1
        if seconds < 0 {
            timer.cancel()
        } else {
            print(seconds)
        }
    }
    timer.resume()
    
  5. 死锁、临界区、竞态条件、优先级反转、并发与并行

    // 自旋锁
    

posted @ 2022-02-23 15:41  weicy  阅读(205)  评论(0编辑  收藏  举报