Skip to content

Instantly share code, notes, and snippets.

@djromero
Forked from seanlilmateus/channel.swift
Last active January 18, 2018 22:31
Show Gist options
  • Save djromero/3a642f86d9947b9ff687 to your computer and use it in GitHub Desktop.
Save djromero/3a642f86d9947b9ff687 to your computer and use it in GitHub Desktop.
golang like channels in swift
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