5 Commits

3 changed files with 21 additions and 15 deletions

View File

@@ -10,5 +10,6 @@ waiter.AddCloseHandler(func() {
nacl.FinalizeStan()
}, false)
waiter.Wait(true)
// blocking wait, if no need to block (with http server, for example), you can omit .Wait() call
waiter.Wait()
```

View File

@@ -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()

View File

@@ -16,11 +16,11 @@ type Waiter struct {
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)
@@ -32,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 {
@@ -63,12 +67,10 @@ func (w *Waiter) Halt(err error) {
}
}
func (w *Waiter) Wait(blockingMode bool) {
w.blockingMode = blockingMode
if blockingMode {
log.Info("Waiting...")
w.waitGroup.Wait()
}
func (w *Waiter) Wait() {
w.blockingMode = true
log.Info("Waiting...")
w.waitGroup.Wait()
}
func (w *Waiter) onSignal(sig os.Signal) {
@@ -78,7 +80,7 @@ func (w *Waiter) onSignal(sig os.Signal) {
func NewWaiter() *Waiter {
w := Waiter{
true,
false,
sync.WaitGroup{},
make([]*CloseHandler, 0),
}