Skip to content

Instantly share code, notes, and snippets.

@groue
Created November 18, 2016 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groue/bc696776a901e03c7b9120ad9441735e to your computer and use it in GitHub Desktop.
Save groue/bc696776a901e03c7b9120ad9441735e to your computer and use it in GitHub Desktop.
A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
final class ReadWriteBox<T> {
var value: T {
get { return read { $0 } }
set { write { $0 = newValue } }
}
init(_ value: T) {
self._value = value
self.queue = DispatchQueue(label: "ReadWriteBox", attributes: [.concurrent])
}
func read<U>(_ block: (T) throws -> U) rethrows -> U {
return try queue.sync {
try block(_value)
}
}
func write<U>(_ block: (inout T) throws -> U) rethrows -> U {
return try queue.sync(flags: [.barrier]) {
try block(&_value)
}
}
private var _value: T
private var queue: DispatchQueue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment