-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.go
34 lines (30 loc) · 867 Bytes
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package async
// A State is a [Signal] that carries a value.
// To retrieve the value, call the Get method.
//
// Calling the Set method of a State, in a [Task] function, updates the value
// and resumes any [Coroutine] that is watching the State.
//
// A State must not be shared by more than one [Executor].
type State[T any] struct {
Signal
value T
}
// NewState creates a new [State] with its initial value set to v.
func NewState[T any](v T) *State[T] {
return &State[T]{value: v}
}
// Get retrieves the value of s.
//
// Without proper synchronization, one should only call this method in
// a [Task] function.
func (s *State[T]) Get() T {
return s.value
}
// Set updates the value of s and resumes any [Coroutine] that is watching s.
//
// One should only call this method in a [Task] function.
func (s *State[T]) Set(v T) {
s.value = v
s.Notify()
}