Created
March 14, 2018 03:04
-
-
Save algal/0f047de3493b34a21026336ba0bf90fd to your computer and use it in GitHub Desktop.
ClojureAgentInSwift.swift
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
| 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