当前位置:   article > 正文

swift 多线程GCD 高级方法 DispatchGroup_swift dispatchgroup

swift dispatchgroup

DispatchGroup


enter和leave 是要成对出现的

  1. //: FROM https://www.anuomob.com
  2. import UIKit
  3. import PlaygroundSupport
  4. //不希望主线程执行完毕就结束
  5. PlaygroundPage.current.needsIndefiniteExecution = true
  6. let workingGroup = DispatchGroup()
  7. let workingQueue = DispatchQueue(label: "request_queue")
  8. workingGroup.enter()
  9. workingQueue.async {
  10. Thread.sleep(forTimeInterval: 1)
  11. print("接口A 数据请求完成")
  12. workingGroup.leave()
  13. }
  14. workingGroup.enter()
  15. workingQueue.async {
  16. Thread.sleep(forTimeInterval: 1)
  17. print("接口B 数据请求完成")
  18. workingGroup.leave()
  19. }
  20. print("我是最开始执行的,异步操作里的打印后执行")
  21. workingGroup.wait()
  22. print("数据A,和数据B的数据请求都已经完毕!开始合并两个接口的数据")

我是最开始执行的,异步操作里的打印后执行

接口A 数据请求完成

接口B 数据请求完成

数据A,和数据B的数据请求都已经完毕!开始合并两个接口的数据

 

简单来说 dispatch source 是一个见识某类型的对象,当这些事件发生时,它自动将一个task放入一个dispatchqueue的执行例程中

Mach port send right state changes.
Mach port receive right state changes.
External process state change.
File descriptor ready for read.
" File descriptor ready for write.
. Filesystem node event.
POSIX signal.
Custom timer.
. Custom event.

下面写一个定时器

  1. //: FROM https://www.anuomob.com
  2. import UIKit
  3. import PlaygroundSupport
  4. //不希望主线程执行完毕就结束
  5. PlaygroundPage.current.needsIndefiniteExecution = true
  6. var seconds = 10
  7. let timer:DispatchSourceTimer = DispatchSource.makeTimerSource(flags:[], queue: DispatchQueue.global())
  8. timer.schedule(deadline: .now(),repeating: 1.0)
  9. timer.setEventHandler{
  10. seconds -= 1
  11. if seconds < 0 {
  12. timer.cancel()
  13. } else {
  14. print(seconds)
  15. }
  16. }
  17. timer.resume()
  1. 9
  2. 8
  3. 7
  4. 6
  5. 5
  6. 4
  7. 3
  8. 2
  9. 1
  10. 0

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/691572
推荐阅读
相关标签
  

闽ICP备14008679号