GCD判断当前代码是否在主队列

2020-05-27  本文已影响0人  欧巴刚弄死他

前言:当你封装一个方法想使它兼容于多线程,但是里面又要同步调用主队列,这时候就要想办法避免线程锁死的问题。

思路:dispatch_get_current_queue()已经被废弃,而且并不能真正判断到。
所幸DispatchQueue有这两个方法:setSpecific和getSpecific,一个是为队列打标签,另一个是取标签,而且支持实例方法和类方法(实际是4个方法)。实例方法是设置和获取具体某个队列的标签,类方法是设置和获取当前队列的标签。以下代码仅适用于swift。

fileprivate let globalMainQueueKey = DispatchSpecificKey<Int>.init()
fileprivate var globalMainQueueValue = 20

自己找个地方初始化

DispatchQueue.main.setSpecific(key: globalMainQueueKey, value: globalMainQueueValue)

调用:

func dispatchMainSync(_ execute:() -> Void) {
    if DispatchQueue.getSpecific(key: globalMainQueueKey) == globalMainQueueValue {
        execute()
    } else {
        DispatchQueue.main.sync(execute: execute)
    }
}
上一篇下一篇

猜你喜欢

热点阅读