//泛型编程是一种面向算法的多态技术
//协议关联类型 - 相当于泛型 associatedtype. 协议不支持泛型指定
/** 当协议里不知道该存储什么类型时, 使用一个关联类型占位的意思 */
protocol Container {
associatedtype ItemType: Equatable //也可以给关联类型遵循协议
mutating func append(_ item: ItemType)
var count: Int {get}
subscript(i: Int) -> ItemType {get}
}
extension Container {
subscript<Indices: Sequence>(indice: Indices) -> [ItemType] where Indices.Iterator.Element == Int {
var result = [ItemType]()
for index in indice {
result.append(self[index])
}
return result
}
}
多线程
//多线程 Thread两种方法
for i in 0..<10 {
Thread.detachNewThread {
print(i)
}
}
class TestThread {
func threadFunction() -> Void {
let thread = Thread(target: self, selector: #selector(threadFunc), object: nil)
thread.start()
}
@objc func threadFunc() {
print("Thread")
}
}
//Operation OperationQueue 简单使用。 和OC的很类似, 其他使用方法参考OC
class OperationClass {
func blockOperation() -> Void {
let op = BlockOperation {
sleep(2)
print("BlockOperation")
}
op.completionBlock = { [weak self] in
print("Test + \(self)")
}
let op2 = BlockOperation(block: {[weak self] in
sleep(1)
self?.opFunc()
})
//operation执行完的回调
op2.completionBlock = {
print("都执行完了")
}
let queue = OperationQueue()
queue.addOperation(op)
queue.addOperation(op2)
}
func opFunc() -> Void {
print("laile")
}
}
let opClass = OperationClass()
opClass.blockOperation()
print("主线程开始执行")
//也可以继承自Operation
class MyOperation: Operation {
override func main() {
sleep(1)
print("Custom Operation")
}
}
GCD
//GCD
//这样简单创建的是串行队列
let serialQueue = DispatchQueue(label: "SerialQueue")
/**label: 队列标志名
qos:一般选默认即可, 有background等模式
attributes:指定串行还是b并发队列
autoreleaseFrequency: 一般选继承类型即可inherit
target:目标队列,可以不设置,系统会自动添加到目标队列里
*/
let queue = DispatchQueue(label: "MyQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
queue.sync {
sleep(1)
print("in queue sync")
}
print("after invoke queue method")
queue.async {
sleep(1)
print("in queue async")
}
print("after invoke queue method")
queue.asyncAfter(deadline: DispatchTime.now() + 1) {
print("asyn after")
}
//GCD Group
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
group.enter()
queue1.async {
sleep(1)
print("1111")
group.leave()
}
group.enter()
queue1.async {
print("22222")
group.leave()
}
print("enter 完成")
//group.wait()
print("wait 是阻塞的,这个最后执行")
group.notify(queue: queue1) {
print("12完成了")
}
print("Notify 是不阻塞的, 会先执行")
//DispatchSource - Timer
var seconds = 10
let queue = DispatchQueue(label: "MyQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags.init(), queue: queue)
timer.schedule(deadline: DispatchTime.now(), repeating: 1)
timer.setEventHandler {
seconds -= 1
if seconds < 0 {
timer.cancel()
}else {
print(seconds)
}
}
timer.resume()
//g多线程保证数组读写完全
class SafeArray {
let queue1 = DispatchQueue(label: "queue1", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
let queue2 = DispatchQueue(label: "queue2", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
let arrayQueue = DispatchQueue(label: "arrayQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
var largeArray = Array(0...10000)
// let lock = NSLock()
// func getLastItem() -> Int? {
// lock.lock()
// var temp = 0
// if largeArray.count > 0 {
// temp = largeArray[largeArray.count - 1]
// }
// lock.unlock()
// return temp
// }
//
// func removeLastItem() -> Void {
// lock.lock()
// largeArray.removeLast()
// lock.unlock()
// }
//更高效的获取方法
func getLastItem() -> Int {
arrayQueue.sync { () -> Int in
var temp = 0
if largeArray.count > 0 {
temp = largeArray[largeArray.count - 1]
}
return temp
}
}
//栅栏函数
func removeLastItem() -> Void {
let workItem = DispatchWorkItem(qos: DispatchQoS.default, flags: DispatchWorkItemFlags.barrier) {
self.largeArray.removeLast()
}
arrayQueue.async(execute: workItem)
}
func testSafeArray() -> Void {
queue1.async {
for _ in 0...10000 {
let index = self.getLastItem()
print(index as Any)
}
}
queue2.async {
for _ in 0...10000 {
self.removeLastItem()
}
}
}
}
let safeArr = SafeArray()
safeArr.testSafeArray()
//栅栏函数使用
DispatchQueue.global().async(group: group, qos: DispatchQoS.default, flags: DispatchWorkItemFlags.barrier) {
}