Created
November 18, 2016 15:43
-
-
Save groue/bc696776a901e03c7b9120ad9441735e to your computer and use it in GitHub Desktop.
A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
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
/// 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