scoop:scoop.core:0.1.0
src/atomic_values.scoop
Selected production source · src/atomic_values.scoop
1
/**2
* A lock-protected cell for any value type, including values containing managed references.3
* Operations copy the whole value under the cell lock.4
*/5
public class Atomic<T: value> public constructor(initial: T) {6
private val lock: AtomicBoolean = AtomicBoolean(false)7
private var value: T = initial9
/**10
* Copies the stored value while holding the cell lock.11
*/12
public fun load(): T {13
var spins = 014
while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {15
spins = spins + 116
if (spins == 64) {17
@Unsafe18
{19
atomicYield()20
}21
spins = 022
}23
}24
val result = value25
lock.store(false, MemoryOrder.Release)26
return result27
}29
/**30
* Replaces the whole value while holding the cell lock.31
*/32
public fun store(value: T) {33
var spins = 034
while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {35
spins = spins + 136
if (spins == 64) {37
@Unsafe38
{39
atomicYield()40
}41
spins = 042
}43
}44
this.value = value45
lock.store(false, MemoryOrder.Release)46
}48
/**49
* Replaces the value under one lock acquisition and returns the previous value.50
*/51
public fun exchange(value: T): T {52
var spins = 053
while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {54
spins = spins + 155
if (spins == 64) {56
@Unsafe57
{58
atomicYield()59
}60
spins = 061
}62
}63
val result = this.value64
this.value = value65
lock.store(false, MemoryOrder.Release)66
return result67
}68
}