Skip to content

Commit 72f5645

Browse files
committed
internal/task: add non-atomic atomic operations
This adds some non-atomic types that have the same interface as the ones in sync/atomic. We currently don't need these to be atomic (because the scheduler is entirely cooperative), but once we add support for a scheduler with multiple threads and/or preemptive scheduling we can trivially add some type aliases under a different build tag in the future when real atomicity is needed for threading.
1 parent b5a8931 commit 72f5645

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package task
2+
3+
// Atomics implementation for cooperative systems. The atomic types here aren't
4+
// actually atomic, they assume that accesses cannot be interrupted by a
5+
// different goroutine or interrupt happening at the same time.
6+
7+
type atomicIntegerType interface {
8+
uintptr | uint32 | uint64
9+
}
10+
11+
type pseudoAtomic[T atomicIntegerType] struct {
12+
v T
13+
}
14+
15+
func (x *pseudoAtomic[T]) Add(delta T) T { x.v += delta; return x.v }
16+
func (x *pseudoAtomic[T]) Load() T { return x.v }
17+
func (x *pseudoAtomic[T]) Store(val T) { x.v = val }
18+
func (x *pseudoAtomic[T]) CompareAndSwap(old, new T) (swapped bool) {
19+
if x.v != old {
20+
return false
21+
}
22+
x.v = new
23+
return true
24+
}
25+
func (x *pseudoAtomic[T]) Swap(new T) (old T) {
26+
old = x.v
27+
x.v = new
28+
return
29+
}
30+
31+
// Uintptr is an atomic uintptr when multithreading is enabled, and a plain old
32+
// uintptr otherwise.
33+
type Uintptr = pseudoAtomic[uintptr]
34+
35+
// Uint32 is an atomic uint32 when multithreading is enabled, and a plain old
36+
// uint32 otherwise.
37+
type Uint32 = pseudoAtomic[uint32]
38+
39+
// Uint64 is an atomic uint64 when multithreading is enabled, and a plain old
40+
// uint64 otherwise.
41+
type Uint64 = pseudoAtomic[uint64]

0 commit comments

Comments
 (0)