-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_value.go
More file actions
35 lines (30 loc) · 754 Bytes
/
shared_value.go
File metadata and controls
35 lines (30 loc) · 754 Bytes
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
35
package main
import (
"sync"
)
// A SharedValue threadsafely shares a value between goroutines.
//
// Access and modification is by Set() and Get() methods. SharedValues should
// be initialised with the NewSharedValue() function.
type SharedValue[T any] struct {
value *T
lock *sync.RWMutex
}
// Return a new initialised SharedValue containing the zero value of T.
func NewSharedValue[T any]() SharedValue[T] {
var lock sync.RWMutex
var val T
return SharedValue[T]{value: &val, lock: &lock}
}
// Set the shared value
func (s *SharedValue[T]) Set(value T) {
s.lock.Lock()
defer s.lock.Unlock()
*s.value = value
}
// Get the current shared value
func (s *SharedValue[T]) Get() T {
s.lock.RLock()
defer s.lock.RUnlock()
return *s.value
}