swift实现一个对象池

1.创建一个对象池

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

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

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

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

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

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信号量类型还是比较简单的,

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)
}

猜你喜欢

转载自www.cnblogs.com/dev-walden/p/10484127.html