Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class Pool<Element>
{
/// Los elementos que gestionamos
public private(set) var elements: [Element]
/// La queue de tipo serial
private let queue: DispatchQueue
/// El semáforo de control de acceso
private let semaphore: DispatchSemaphore
/// Elementos disponibles en un momento dado
public var elementsAvailables: Int
{
var count = 0
self.queue.sync
{
count = self.elements.count
}
return count
}
/**
Nuevo Pool
*/
public init(elements: [Element])
{
self.elements = elements
self.queue = DispatchQueue(label: "com.desappstre.Pool./serial_queue")
self.semaphore = DispatchSemaphore(value: elements.count)
}
/**
Recupera un elemento
*/
public func getElement() -> Element?
{
// Esperamos a que haya un elemento disponible
// y decrementamos el contador del semáforo
self.semaphore.wait()
var the_element: Element?
self.queue.sync
{
the_element = self.elements.removeFirst()
}
return the_element
}
/**
*/
public func restore(_ element: Element) -> Void
{
self.queue.async
{
self.elements.append(element)
// Aumentamos el contador del semáforo
self.semaphore.signal()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment