-
-
Save djromero/3a642f86d9947b9ff687 to your computer and use it in GitHub Desktop.
golang like channels 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 XCPlayground | |
import Foundation | |
import UIKit | |
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_async(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<String> = Channel() | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { | |
for index in 0...10 { | |
chan.write("ping \(index)") | |
let pong = chan.recv() | |
print("[A] \(index): \(pong)") | |
NSThread.sleepForTimeInterval(0.1) | |
} | |
} | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { | |
for index in 0...10 { | |
let ping = chan.recv() | |
print("[B] \(index): \(ping)") | |
chan.write("pong \(index)") | |
} | |
} | |
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment