Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed59ea1d0a | ||
|
|
9eec782920 | ||
|
|
f7d5b41aba | ||
|
|
7f494b3d57 | ||
|
|
ac0f979ef9 | ||
|
|
a980f1f8d2 |
@@ -10,5 +10,6 @@ waiter.AddCloseHandler(func() {
|
||||
nacl.FinalizeStan()
|
||||
}, false)
|
||||
|
||||
// blocking wait, if no need to block (with http server, for example), you can omit .Wait() call
|
||||
waiter.Wait()
|
||||
```
|
||||
@@ -1,8 +1,11 @@
|
||||
package grawt
|
||||
|
||||
import "sync"
|
||||
|
||||
type CloseHandler struct {
|
||||
sync.Mutex
|
||||
waiter *Waiter
|
||||
Quit chan bool
|
||||
Quit chan struct{}
|
||||
active bool
|
||||
autoDone bool
|
||||
handlerFunc *func()
|
||||
|
||||
26
waiter.go
26
waiter.go
@@ -9,17 +9,18 @@ import (
|
||||
)
|
||||
|
||||
type Waiter struct {
|
||||
blockingMode bool
|
||||
waitGroup sync.WaitGroup
|
||||
closeHandlers []*CloseHandler
|
||||
}
|
||||
|
||||
func (w *Waiter) addHandler(f *func(), autoDone bool) *CloseHandler {
|
||||
ch := CloseHandler{
|
||||
w,
|
||||
make(chan bool, 1),
|
||||
true,
|
||||
autoDone,
|
||||
f,
|
||||
waiter: w,
|
||||
Quit: make(chan struct{}, 1),
|
||||
active: true,
|
||||
autoDone: autoDone,
|
||||
handlerFunc: f,
|
||||
}
|
||||
w.waitGroup.Add(1)
|
||||
w.closeHandlers = append(w.closeHandlers, &ch)
|
||||
@@ -31,11 +32,15 @@ func (w *Waiter) terminateHandler(h *CloseHandler, forceWaitGroupDone bool) {
|
||||
if h.handlerFunc != nil && *h.handlerFunc != nil {
|
||||
(*h.handlerFunc)()
|
||||
}
|
||||
h.Quit <- true
|
||||
h.Lock()
|
||||
if h.active {
|
||||
close(h.Quit)
|
||||
}
|
||||
if h.autoDone || forceWaitGroupDone {
|
||||
w.waitGroup.Done()
|
||||
}
|
||||
h.active = false
|
||||
h.Unlock()
|
||||
}
|
||||
|
||||
func (w *Waiter) AddCloseHandler(f func(), waitForChannel bool) *CloseHandler {
|
||||
@@ -53,9 +58,17 @@ func (w *Waiter) Halt(err error) {
|
||||
} else {
|
||||
log.Info("Program was terminated gracefully.")
|
||||
}
|
||||
if !w.blockingMode {
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
} else {
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Waiter) Wait() {
|
||||
w.blockingMode = true
|
||||
log.Info("Waiting...")
|
||||
w.waitGroup.Wait()
|
||||
}
|
||||
@@ -67,6 +80,7 @@ func (w *Waiter) onSignal(sig os.Signal) {
|
||||
|
||||
func NewWaiter() *Waiter {
|
||||
w := Waiter{
|
||||
false,
|
||||
sync.WaitGroup{},
|
||||
make([]*CloseHandler, 0),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user