swift基础之GCD

原创
2021/04/19 12:17
阅读数 53

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)
        }
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部