Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Playground - noun: a place where people can play */
/* This test does nothing in the playground. Not sure why it does not work, but
* I'm not that surprised it doesn't. */
import Foundation
class Channel<T> {
var stream: Array<T>
let queue: dispatch_queue_t
let semaphore: dispatch_semaphore_t
init() {
self.stream = []
self.semaphore = dispatch_semaphore_create(0)
self.queue = dispatch_queue_create("channel.queue.", DISPATCH_QUEUE_CONCURRENT)
}
func write(value: T) {
dispatch_sync(self.queue) {
self.stream.append(value)
dispatch_semaphore_signal(self.semaphore)
}
}
func recv() -> T {
var result:T?
dispatch_sync(self.queue) {
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
result = self.stream.removeAtIndex(0)
}
return result!
}
}
let chan = Channel<Int>()
let delay = 1.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
chan.write(1)
println(chan.recv())
chan.write(2)
println(chan.recv())
dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
chan.write(5)
})
chan.write(3)
chan.write(4)
println(chan.recv())
println(chan.recv())
println(chan.recv())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.