Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
public struct Song
{
public var title: String
public var album: String
public var artist: String
public init(titled title: String, fromAlbum album: String, by artist: String)
{
self.title = title
self.album = album
self.artist = artist
}
}
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
}
/**
Devuelve un objeto al Pool
*/
public func restore(_ element: Element) -> Void
{
self.queue.async
{
self.elements.append(element)
// Aumentamos el contador del semáforo
self.semaphore.signal()
}
}
}
//
// MARK: - Playground
//
//
// Preparamos las canciones
//
let song1 = Song(titled: "High in Life", fromAlbum: "High on Life - Single", by: "Martin Garrix")
let song2 = Song(titled: "Song 2", fromAlbum: "Blur", by: "Blur")
let song3 = Song(titled: "Forever", fromAlbum: "Love Is Dead", by: "CHVRCHES")
let song4 = Song(titled: "House On Fire", fromAlbum: "Wolves", by: "Rise Against")
let songs = [ song1, song2, song3, song4 ]
//
// Las cargamos en el Pool
//
let pool = Pool(elements: songs)
let playSong1 = pool.getElement()
let playSong2 = pool.getElement()
let playSong3 = pool.getElement()
let playSong4 = pool.getElement()
// Vemos que no queda ninguna canción disponible
print(pool.elementsAvailables) // 0
//
// No quedan canciones disponibles
//
// Se quedará esperando hasta que devolvamos
// alguna al Pool
//
//
let playSong5 = pool.getElement() // Comentar esta línea para poder continuar con la ejecución
//
// Vamos a devolver las canciones
//
pool.restore(song2)
print(pool.elementsAvailables) // 1
pool.restore(song4)
print(pool.elementsAvailables) // 2
pool.restore(song1)
print(pool.elementsAvailables) // 3
pool.restore(song3)
print(pool.elementsAvailables) // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment