(Swift)多线程-GCD

1)DispatchGroup()
let taskQueue = DispatchQueue.global()
let taskGroup = DispatchGroup()

taskGroup.enter()
taskQueue.async {
    sleep(1)
    print("耗时异步任务A")
    taskGroup.leave()
}

taskGroup.enter()
taskQueue.async {
    sleep(1)
    print("耗时异步任务B")
    taskGroup.leave()
}

taskGroup.notify(queue: taskQueue) {
    print("A和B两个任务都完成后,再执行后续任务")
}
2)DispatchSource提供的定时器方法
var taskTarget = 0
let taskQueue = DispatchQueue.global()

let taskTimer = DispatchSource.makeTimerSource(flags: [], queue: taskQueue)
taskTimer.schedule(deadline: .now(), repeating: 1)
taskTimer.setEventHandler {
    taskTarget += 1
    if taskTarget == 10 {
        taskTimer.cancel()
    }else{
        print(taskTarget)
    }
}
taskTimer.resume()
3)Array数组读取加锁安全操作
let arrayQueue = DispatchQueue(label: "arrayQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)

let taskQueue = DispatchQueue.global()
var taskArray = Array(1...1000)
//let lock = NSLock()

func getLastElement() -> Int{
    return arrayQueue.sync { () -> Int in
        if taskArray.count > 0 {
            return taskArray[taskArray.count - 1]
        }
        return -1
    }
}

func removeLastElement(){
    let workItem = DispatchWorkItem(qos: DispatchQoS.default, flags: DispatchWorkItemFlags.barrier) {
        taskArray.removeLast()
    }
    arrayQueue.async(execute: workItem)
}

taskQueue.async {
    for _ in taskArray {
        removeLastElement()
    }
}

taskQueue.async {
    for _ in taskArray {
        print( getLastElement())
    }
}

你可能感兴趣的:((Swift)多线程-GCD)