美文网首页
iOS多线程之GCD的使用

iOS多线程之GCD的使用

作者: 土豆吞噬者 | 来源:发表于2019-08-28 18:31 被阅读0次

串行队列和并行队列

在系统底层,程序是运行在线程之中的,为了简化线程操作,GCD封装了队列的概念用来处理任务。串行队列一般只分配一个线程,所有任务按照进入的先后顺序来处理,并行队列至少分配一个线程,多个任务可以同时处理。

创建队列

convenience init(label: String, qos: DispatchQoS = .unspecified, attributes: DispatchQueue.Attributes = [], autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil)
  • label:用于在调试时标记队列的标签,建议使用类似com.example.myqueue的名称。
  • qos:队列的服务质量级别,用于确定队列执行任务的优先级。
  • attributes:队列的属性,concurrent表示队列为并行队列(默认为串行队列),initiallyInactive表示队列创建后不会自动执行,需要调用activate方法才会执行(默认会自动执行)。
  • autoreleaseFrequency:表示队列自动释放对象的频率。
  • target:队列的目标队列,用于将队列的任务重定向到目标队列执行,目标队列的优先级影响队列的优先级。目标队列不能有重复依赖,例如A队列的目标队列是B,B队列的目标队列是A。

QoS级别

一共有5 个不同的 QoS 级别,优先级从高往低排序如下:

  • userInteractive: 用户交互相关的,例如动画,事件处理,界面更新,优先级最高。
  • userInitiated: 用户执行操作需要立即得到结果的,例如用户点击一封邮件要获取邮件内容。
  • default:默认的级别。
  • utility: 用户需要一些时间才能得到结果的,例如下载文件,完成后通知用户。
  • background: 工作要很长时间且用户看不见的,例如索引,同步操作和备份等,优先级最低。

还有一个特殊的QoS级别unspecified,这个时候系统根据环境自动推断QoS级别。

主队列和全局队列

主队列是一个串行队列,它主要处理 UI 相关任务,也可以处理其他类型任务,但为了性能考虑,尽量让主队列执行 UI 相关或少量不耗时的操作。

全局队列是一个并行队列,一共有5个全局队列对于不同的QoS级别。

避免创建过多的线程

当并行队列的任务阻塞线程时,系统会创建其它线程来运行排队的任务,如果阻塞线程的任务过多,系统可能会耗尽线程,所以尽量不要在并行队列的任务中阻塞线程。

每个队列都占用线程资源,创建过多的并行队列会消耗线程资源,尽可能使用全局队列而不是创建并行队列,对于串行任务,请将串行队列的目标队列设置为全局队列,这样可以减少队列创建的线程数量。

同步执行和异步执行

调用队列的sync方法同步执行任务,任务执行完了sync方法才会返回,调用当前队列的sync方法会导致死锁,sync方法会尽可能在当前线程上执行任务,主队列的任务总是在主线程上运行。

调用队列的async方法异步执行任务,该方法不会阻塞当前线程,任务在其它线程上运行。

同步执行串行队列任务:

    func printCurrentThread() {
        print("current thread: \(Thread.current), is main thread: \(Thread.isMainThread)")
    }
    
    func print123(_ tag:String){
        for i in 0...2{
          print(tag+String(i+1))
          usleep(100*1000)
        }
        
    }

    
    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue")
        queue.sync {
            self.printCurrentThread()
            self.print123("🍎")
            
        }
        print("execute second task")
        queue.sync {
            self.printCurrentThread()
            self.print123("🌰")
        }
    }

结果:

current thread: <NSThread: 0x600002caa8c0>{number = 1, name = main}, is main thread: true
🍎1
🍎2
🍎3
execute second task
current thread: <NSThread: 0x600002caa8c0>{number = 1, name = main}, is main thread: true
🌰1
🌰2
🌰3

异步执行串行队列任务:

    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue")
        queue.async {
            self.printCurrentThread()
            self.print123("🍎")
            
        }
        print("execute second task")
        queue.async {
            self.printCurrentThread()
            self.print123("🌰")
        }
    }

结果:

execute second task
current thread: <NSThread: 0x60000278eac0>{number = 3, name = (null)}, is main thread: false
🍎1
🍎2
🍎3
current thread: <NSThread: 0x60000278eac0>{number = 3, name = (null)}, is main thread: false
🌰1
🌰2
🌰3

同步执行并行队列任务:

    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue",attributes:[.concurrent])
        queue.sync {
            self.printCurrentThread()
            self.print123("🍎")
            
        }
        print("execute second task")
        queue.sync {
            self.printCurrentThread()
            self.print123("🌰")
        }
    }

结果:

current thread: <NSThread: 0x600000141a00>{number = 1, name = main}, is main thread: true
🍎1
🍎2
🍎3
execute second task
current thread: <NSThread: 0x600000141a00>{number = 1, name = main}, is main thread: true
🌰1
🌰2
🌰3

异步执行并行队列任务:

    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue",attributes:[.concurrent])
        queue.async {
            self.printCurrentThread()
            self.print123("🍎")
            
        }
        print("execute second task")
        queue.async {
            self.printCurrentThread()
            self.print123("🌰")
        }
    }

结果:

execute second task
current thread: <NSThread: 0x600002377980>{number = 3, name = (null)}, is main thread: false
🍎1
current thread: <NSThread: 0x600002377bc0>{number = 4, name = (null)}, is main thread: false
🌰1
🍎2
🌰2
🍎3
🌰3

延迟执行

使用asyncAfter可以延迟执行任务。

    @IBAction func testButtonDidClick(_ sender: Any) {
        print("print hello after 5 seconds")
        DispatchQueue.global().asyncAfter(deadline: .now()+5, execute: {print("hello")})
    }

栅栏任务

栅栏任务的特性是它会先等待队列中已有的任务执行完成后再执行,在它之后加入的任务也必须等栅栏任务执行完后才能执行,创建栅栏任务的方法是添加barrier标志。

    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue",attributes:[.concurrent])
        queue.async {
            self.printCurrentThread()
            self.print123("🍎")
            
        }
        queue.async {
            self.printCurrentThread()
            self.print123("🌰")
        }
        queue.async(flags:.barrier,execute:{
            self.printCurrentThread()
            self.print123("🍌")
            })
        queue.async {
            self.printCurrentThread()
            self.print123("🍓")
            
        }
        queue.async {
            self.printCurrentThread()
            self.print123("🍊")
        }
    }

结果:

current thread: <NSThread: 0x600002ab4540>{number = 3, name = (null)}, is main thread: false
current thread: <NSThread: 0x600002abd080>{number = 4, name = (null)}, is main thread: false
🍎1
🌰1
🍎2
🌰2
🍎3
🌰3
current thread: <NSThread: 0x600002abd080>{number = 4, name = (null)}, is main thread: false
🍌1
🍌2
🍌3
current thread: <NSThread: 0x600002abd080>{number = 4, name = (null)}, is main thread: false
🍓1
current thread: <NSThread: 0x600002ab4540>{number = 3, name = (null)}, is main thread: false
🍊1
🍓2
🍊2
🍓3
🍊3


迭代任务

concurrentPerform 方法将任务放在多个线程中执行指定迭代次数,它会等待所有迭代执行完才会返回。

    @IBAction func testButtonDidClick(_ sender: Any) {
        let queue=DispatchQueue(label: "com.studyswift.queue",attributes:[.concurrent])
        queue.async {
            DispatchQueue.concurrentPerform(iterations: 5, execute: {index in
                self.printCurrentThread()
                print(index)
            })
        }
    }

结果:

current thread: <NSThread: 0x600002178900>{number = 5, name = (null)}, is main thread: false
0
current thread: <NSThread: 0x60000214b380>{number = 3, name = (null)}, is main thread: false
current thread: <NSThread: 0x600002178900>{number = 5, name = (null)}, is main thread: false
4
current thread: <NSThread: 0x60000214b340>{number = 6, name = (null)}, is main thread: false
1
current thread: <NSThread: 0x600002178480>{number = 4, name = (null)}, is main thread: false
2
3

相关文章

网友评论

      本文标题:iOS多线程之GCD的使用

      本文链接:https://www.haomeiwen.com/subject/nuwmectx.html