Last active
August 14, 2016 00:43
-
-
Save loganwright/3eadb0a16ce077e18129a5f9f91fe5d0 to your computer and use it in GitHub Desktop.
Possible Thread Queue
This file contains hidden or 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
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?() | |
} | |
} |
This file contains hidden or 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
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