swift 多线程GCD 高级方法 DispatchGroup

DispatchGroup


enter和leave 是要成对出现的

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

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

let workingGroup = DispatchGroup()
let workingQueue = DispatchQueue(label: "request_queue")
workingGroup.enter()
workingQueue.async {
    Thread.sleep(forTimeInterval: 1)
    print("接口A 数据请求完成")
    workingGroup.leave()
}

workingGroup.enter()
workingQueue.async {
    Thread.sleep(forTimeInterval: 1)
    print("接口B 数据请求完成")
    workingGroup.leave()
}

print("我是最开始执行的,异步操作里的打印后执行")
workingGroup.wait()
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.

下面写一个定时器

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

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

var seconds = 10
let timer:DispatchSourceTimer = 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()
9
8
7
6
5
4
3
2
1
0

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/108325472