-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
43 lines (38 loc) · 851 Bytes
/
service.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
package services
import (
"errors"
"sync"
"sync/atomic"
)
type ServiceLifeCycle interface {
Initialize(arguments ...interface{}) error
UnInitialize(arguments ...interface{}) error
}
type InitHelper struct {
init uint32
lock sync.RWMutex
}
func (s *InitHelper) CallInitialize(f func() error) error {
if atomic.LoadUint32(&s.init) == 1 {
return errors.New("already initialize")
}
s.lock.Lock()
defer s.lock.Unlock()
if s.init == 0 {
defer atomic.StoreUint32(&s.init, 1)
return f()
}
return errors.New("already initialize")
}
func (s *InitHelper) CallUnInitialize(f func() error) error {
if atomic.LoadUint32(&s.init) == 0 {
return errors.New("already uninitialize")
}
s.lock.Lock()
defer s.lock.Unlock()
if s.init == 1 {
defer atomic.StoreUint32(&s.init, 0)
return f()
}
return errors.New("already uninitialize")
}