Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created September 8, 2023 08:45
Show Gist options
  • Save laevandus/5a1250c8c99645465bb2da1db9a6a147 to your computer and use it in GitHub Desktop.
Save laevandus/5a1250c8c99645465bb2da1db9a6a147 to your computer and use it in GitHub Desktop.
actor DiapasonTracker {
private var minValue: Int = 0
private var maxValue: Int = 0
func receive(_ batch: [Int]) {
guard let batchMin = batch.min() else { return }
minValue = min(minValue, batchMin)
guard let batchMax = batch.max() else { return }
maxValue = max(maxValue, batchMax)
}
// Here diapason can't be accessed
// at the same time when receive() is
// the middle of updating
// minValue and/or maxValue.
// Using class instead of actor would
// allow one thread to update values
// while another is accessing diapason
// property which leads to inconsistencies.
var diapason: Int {
maxValue - minValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment