-
Notifications
You must be signed in to change notification settings - Fork 0
/
safeint.go
45 lines (36 loc) · 881 Bytes
/
safeint.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
35
36
37
38
39
40
41
42
43
44
45
package parallel
import "sync"
// safeInt wraps an integer type and exposes methods to safely read/write to the
// integer value from multiple threads.
type safeInt struct {
value int
mutex sync.Mutex
}
// get gets the integer value.
func (s *safeInt) get() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.value
}
// set sets the integer value and returns the result.
func (s *safeInt) set(n int) int {
s.mutex.Lock()
defer s.mutex.Unlock()
s.value = n
return s.value
}
// add adds the input parameter to the integer value and returns the result.
func (s *safeInt) add(n int) int {
s.mutex.Lock()
defer s.mutex.Unlock()
s.value += n
return s.value
}
// subtract subtracts the input parameter from the integer value and returns the
// result.
func (s *safeInt) subtract(n int) int {
s.mutex.Lock()
defer s.mutex.Unlock()
s.value -= n
return s.value
}