Created
October 20, 2019 11:04
-
-
Save kongzii/2cf88aed189747667dc5d61282a0b7c9 to your computer and use it in GitHub Desktop.
Thread safe Queue implementation in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public enum QueueType { | |
case lifo | |
} | |
public class Queue<T> { | |
var maxSize: Int? = nil | |
var elements: Array<T> = [] | |
var type: QueueType = QueueType.lifo | |
let semaphore = DispatchSemaphore(value: 1) | |
var done: Bool = false | |
public init(maxSize: Int? = nil, type: QueueType = QueueType.lifo) { | |
self.maxSize = maxSize | |
self.type = type | |
} | |
public var count: Int { | |
return self.elements.count | |
} | |
public var isEmpty: Bool { | |
return self.elements.isEmpty | |
} | |
public var isFull: Bool { | |
return self.maxSize != nil && self.count == self.maxSize! | |
} | |
public var isDone: Bool { | |
get { | |
return self.done | |
} | |
set { | |
self.done = newValue | |
} | |
} | |
public func add(_ element: T, timeout: DispatchTime = DispatchTime.distantFuture) -> Bool { | |
let state = self.semaphore.wait(timeout: timeout) | |
defer { self.semaphore.signal() } | |
if state == .timedOut || self.isFull { | |
return false | |
} | |
self.elements.append(element) | |
return true | |
} | |
public func pop(timeout: DispatchTime = DispatchTime.distantFuture) -> T? { | |
let state = self.semaphore.wait(timeout: timeout) | |
defer { self.semaphore.signal() } | |
if state == .timedOut || self.isEmpty { | |
return nil | |
} | |
switch self.type { | |
case QueueType.lifo: | |
return self.elements.removeLast() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment