Skip to content

Instantly share code, notes, and snippets.

@loganwright
Last active August 14, 2016 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loganwright/3eadb0a16ce077e18129a5f9f91fe5d0 to your computer and use it in GitHub Desktop.
Save loganwright/3eadb0a16ce077e18129a5f9f91fe5d0 to your computer and use it in GitHub Desktop.
Possible Thread Queue
public class Queue {
private var strand: Strand! = nil
private var queue: [Strand.Closure] = []
private let lock = Lock()
public init(_ operation: Strand.Closure? = nil) throws {
if let operation = operation { queue.append(operation) }
strand = try Strand { [weak self] in
while let welf = self {
welf.fire()
}
}
}
public func add(_ operation: () -> Void) {
lock.locked {
queue.append(operation)
}
}
private func fire() {
var next: Strand.Closure? = nil
lock.locked {
guard !queue.isEmpty else { return }
next = queue.removeFirst()
}
// don't run operation in lock or `add` could block calling queue
next?()
}
}
func testQueue() throws {
var collection = [0]
let strand = try Queue {
sleep(1)
collection.append(1)
}
collection.append(2)
sleep(2)
XCTAssert(collection == [0, 2, 1])
strand.add {
sleep(1)
collection.append(3)
}
collection.append(4)
sleep(2)
XCTAssert(collection == [0, 2, 1, 4, 3])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment