How to use GCD in swift
This article mainly introduces "how to use GCD in swift". In daily operation, I believe many people have doubts about how to use GCD in swift. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use GCD in swift". Next, please follow the editor to study!
Grand Central Dispath (GCD)
GCD adopts the mode of task + queue, which is easy to use, high efficiency and good performance.
/ / concurrent parallel 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 ("An and B done")} print ("other") / * first other A done B done An 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..