千家信息网

如何使用swift中的GCD

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,这篇文章主要介绍"如何使用swift中的GCD",在日常操作中,相信很多人在如何使用swift中的GCD问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"如何使用swift
千家信息网最后更新 2025年02月05日如何使用swift中的GCD

这篇文章主要介绍"如何使用swift中的GCD",在日常操作中,相信很多人在如何使用swift中的GCD问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"如何使用swift中的GCD"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Grand Central Dispath(GCD)

GCD是采用任务+队列的方式,有易用、效率高、性能好的特点

//concurrent 并行let queue = DispatchQueue(    label: "myQueue",    qos: DispatchQoS.default,    attributes: DispatchQueue.Attributes.concurrent,    autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,    target: nil)//syncqueue.sync {    sleep(1)    print("in queue sync")}//asyncqueue.async {    sleep(1)    print("in queue async")}//asyncAfterqueue.asyncAfter(deadline: .now() + 1) {    print("in queue asyncAfter")}print("after invoke queue method")/* in queue sync after invoke queue method in queue async in queue asyncAfter */

DispatchGroup-wait

//DispatchGroup-waitlet workingGroup = DispatchGroup()let workingQueue = DispatchQueue(label: "request_queue")workingGroup.enter()workingQueue.async {    sleep(1)    print("A done")    workingGroup.leave()}workingGroup.enter()workingQueue.async {    print("B done")    workingGroup.leave()}print("first")//workingGroup.wait()//print("last")/* first A done B done last */

DispatchGroup-notify

//DispatchGroup-notifyworkingGroup.notify(queue: workingQueue) {    print("A and B done")}print("other")/* first other A done B done A and B done */

DispatchSource-Timer

//DispatchSource-Timervar seconds = 10let 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 */

实现一个线程安全的Array的读和写

//实现一个线程安全的Array的读和写var array = Array(0...1000)let lock = NSLock()func getLastItem() -> Int? {    lock.lock()    var temp: Int? = nil    if array.count > 0 {        temp = array[array.count - 1]    }    lock.unlock()    return temp}func removeLastItem() {    lock.lock()    array.removeLast()    lock.unlock()}queue.async {    for _ in 0..<1000{        removeLastItem()    }}queue.async {    for _ in 0..<1000 {        if let item = getLastItem() {            print(item)        }    }}

到此,关于"如何使用swift中的GCD"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0