(Swift) Multi-thread-GCD

created at 11-14-2021 views: 2

1)DispatchGroup()

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

taskGroup.enter()
taskQueue.async {
     sleep(1)
     print("Time-consuming asynchronous task A")
     taskGroup.leave()
}

taskGroup.enter()
taskQueue.async {
     sleep(1)
     print("Time-consuming asynchronous task B")
     taskGroup.leave()
}

taskGroup.notify(queue: taskQueue) {
     print("After both tasks A and B are completed, perform subsequent tasks")
}

2) Timer method provided by 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 read and lock security operation

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())
    }
}
created at:11-14-2021
edited at: 11-14-2021: