swift实现一个对象池

1.建立一个对象池

对象池:对象池通常用来管理一组可重用的对象, 这些对象的集合叫作对象池。 组件能够从对象池中借用对象, 完成一些任务以后将它归还给对象池。 返回的对象用于知足调用组件的后续请求, 请求能够来自一个组件, 也能够来自多个组件。数组

要实现这样一个功能, 须要注意两点: 1.处理好并发请求;2.确保每次请求都能获取到对象。并发

对于第一个问题, 能够使用同步队列, 进行并发保护。app

对于第二个问题, 能够使用DispatchSemaphore来控制信号量,若是数组中有值则进入队列取值,若是没有可用对象则等待一直到有可用对象。async

一个简单的对象池的实现方案以下所示:spa

class Pool<T> {
    private var data = [T]()
    private var arrayQueue = dispatch_queue_serial_t(label: "arrayQ")
    private var semaphore: DispatchSemaphore
    
    init(items: [T]) {
        data.reserveCapacity(items.count)
        data.append(contentsOf: items)
        semaphore = DispatchSemaphore(value: items.count)
    }
    
    func getItemFromPool() -> T {
        var result: T?
        if semaphore.wait(timeout: DispatchTime.distantFuture) == 0 {
            arrayQueue.sync {
                result = data.popLast()
            }
        }
    }
    
    func returnToPool(item: T) {
        arrayQueue.async {
            self.data.append(contentsOf: item)
            semaphore.signal()
        }
    }
}

2: DispatchSemaphore

DispatchSemaphore信号量类型仍是比较简单的,code

open class DispatchSemaphore : DispatchObject {
}

/// dispatch_semaphore
extension DispatchSemaphore {
    //提升信号量
    public func signal() -> Int
    //等待下降信号量
    public func wait()

    public func wait(timeout: DispatchTime) -> DispatchTimeoutResult

    public func wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult
}

extension DispatchSemaphore {
    //建立信号量,参数:信号量的初值,若是小于0则会返回NULL
    @available(iOS 4.0, *)
    public /*not inherited*/ init(value: Int)
}
相关文章
相关标签/搜索