swift GCD 基本操作

  • sync
  • async
  • asyncAfter

GCD-串行 vs 并行

swift GCD 基本操作_第1张图片

GCD-同步 vs 异步

swift GCD 基本操作_第2张图片

GCD- sync

swift GCD 基本操作_第3张图片

提交任务到当前队列里,并且直到任务完成,当前队列才会返回

GCD-async

调度一个任务区立即执行

但是不用等任务完成就会直接返回

code

//: FROM  https://www.anuomob.com

import UIKit
import PlaygroundSupport
//不希望主线程执行完毕就结束
PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
queue.sync {
     sleep(1)
    print("in queue sync")
}
print("after invo queue method")



queue.async {
    sleep(1)
    print("in queue async")
}
print("after invo queue method2")
in queue sync
after invo queue method
after invo queue method2
in queue async
//: FROM  https://www.anuomob.com

import UIKit
import PlaygroundSupport
//不希望主线程执行完毕就结束
PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
queue.asyncAfter(deadline: .now()+1, execute: {
    print("in asyncAfter")
})

print("afger invok queue method ")
afger invok queue method 
in asyncAfter

 

你可能感兴趣的:(#,swift)