温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用swift中的GCD

发布时间:2021-10-13 09:40:02 来源:亿速云 阅读:142 作者:iii 栏目:编程语言

这篇文章主要介绍“如何使用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)

//sync
queue.sync {
    sleep(1)
    print("in queue sync")
}

//async
queue.async {
    sleep(1)
    print("in queue async")
}

//asyncAfter
queue.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-wait
let 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-notify
workingGroup.notify(queue: workingQueue) {
    print("A and B done")
}
print("other")

/*
 first
 other
 A done
 B done
 A and B done
 */

DispatchSource-Timer

//DispatchSource-Timer
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
 */

实现一个线程安全的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”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI