Scoop API

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 */
5public class Atomic<T: value> public constructor(initial: T) {
6 private val lock: AtomicBoolean = AtomicBoolean(false)
7 private var value: T = initial
9 /**
10 * Copies the stored value while holding the cell lock.
11 */
12 public fun load(): T {
13 var spins = 0
14 while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {
15 spins = spins + 1
16 if (spins == 64) {
17 @Unsafe
18 {
19 atomicYield()
20 }
21 spins = 0
22 }
23 }
24 val result = value
25 lock.store(false, MemoryOrder.Release)
26 return result
27 }
29 /**
30 * Replaces the whole value while holding the cell lock.
31 */
32 public fun store(value: T) {
33 var spins = 0
34 while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {
35 spins = spins + 1
36 if (spins == 64) {
37 @Unsafe
38 {
39 atomicYield()
40 }
41 spins = 0
42 }
43 }
44 this.value = value
45 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 = 0
53 while (!lock.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {
54 spins = spins + 1
55 if (spins == 64) {
56 @Unsafe
57 {
58 atomicYield()
59 }
60 spins = 0
61 }
62 }
63 val result = this.value
64 this.value = value
65 lock.store(false, MemoryOrder.Release)
66 return result
67 }