Skip to content

Instantly share code, notes, and snippets.

@algal
Created March 14, 2018 03:04
Show Gist options
  • Select an option

  • Save algal/0f047de3493b34a21026336ba0bf90fd to your computer and use it in GitHub Desktop.

Select an option

Save algal/0f047de3493b34a21026336ba0bf90fd to your computer and use it in GitHub Desktop.
ClojureAgentInSwift.swift
import Foundation
/*
Same API as Clojure's agents, but sadly not based on a lockless compare-and-swap operation since Swift doesn not provide one yet.
*/
class Agent<T>
{
private let q = DispatchQueue.init(label:"readwrite")
private let computeQ = DispatchQueue.init(label: "compute")
private var value:T
init(initial:T) {
self.value = initial
}
/// asynchronously update the value
func send(f:@escaping ((T)->T)) -> Void
{
self.computeQ.async {
let oldval = self.read()
let newval = f(oldval)
self.q.async {
self.value = newval
}
}
}
func read() -> T
{
return self.q.sync(execute: { () -> T in
return self.value
})
}
func await() {
self.q.sync(execute: {})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment