多线程开发 - 异步
public typealias Task = () -> Void
public class Asyncs {
public static func async(_ task: @escaping Task) {
_async(task)
}
public static func async(_ task: @escaping Task,
_ mainTask: @escaping Task) {
_async(task, mainTask)
}
private static func _async(_ task: @escaping Task,
_ mainTask: Task? = nil) {
let item = DispatchWorkItem(block: task)
DispatchQueue.global().async(execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
}
}
Asyncs.async({
print(1, Thread.current)
}) {
print(2, Thread.current)
}
1 <NSThread: 0x6000033ec540>{number = 3, name = (null)}
2 <NSThread: 0x600003383bc0>{number = 1, name = main}
多线程开发 - 延迟
public typealias Task = () -> Void
public class Asyncs {
@discardableResult
public static func delay(_ seconds: Double,
_ block: @escaping Task) -> DispatchWorkItem {
let item = DispatchWorkItem(block: block)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
return item
}
}
Asyncs.delay(3) {
print(1)
}
多线程开发 - 异步延迟
public typealias Task = () -> Void
public class Asyncs {
@discardableResult
public static func asyncDelay(_ seconds: Double,
_ task: @escaping Task) -> DispatchWorkItem {
let item = _asyncDelay(seconds, task)
return item
}
@discardableResult
public static func asyncDelay(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: @escaping Task) -> DispatchWorkItem {
let item = _asyncDelay(seconds, task, mainTask)
return item
}
private static func _asyncDelay(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: Task? = nil) -> DispatchWorkItem {
let item = DispatchWorkItem(block: task)
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
return item
}
}
print(1)
Asyncs.asyncDelay(3, {
print(2)
}) {
print(3)
}
- 返回DispatchWorkItem,是因为可以cancel
多线程开发 - once
- dispatch_once在Swift中已被启用,取而代之可以用属性类型或者全局变量\常量
- 默认自带 lazy + dispatch_once效果
let age1: Int = {
print(666)
return 10
}()
class ViewController: UIViewcontroller {
static let age2: Int = {
print(888)
return 20
}()
override func viewDidLoad() {
super.viewDidLoad()
print(age1)
print(age1)
// 666 10 10
print(ViewController.age2)
print(ViewController.age2)
// 888 20 20
}
}
public struct Cache {
private static var data = [String: Any]()
// private static var lock = DispatchSemaphore(value: 1)
// private static var lock = NSLock()
private static var lock = NSRecursiveLock()
public static func get(_ key: String) -> Any? {
return data[key]
}
public static func set(_ key: String, _ value: Any) {
// lock.wait()
// defer {
// lock.signal()
// }
lock.lock()
defer {
lock.unlock()
}
data[key] = value
}
}