Skip to content

Commit

Permalink
update the exit wait
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Jun 17, 2024
1 parent 2cef4a4 commit f47b5c3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
33 changes: 25 additions & 8 deletions assists/initexit.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,33 @@ import (
"fmt"
"log/slog"
"runtime"
"sync/atomic"
)

var TrimPkgFile func(string) string

var (
initfuncs []function
exitfuncs []function

exitednum uint32
exitedch = make(chan struct{})
)

func OnInit(skip int, f func()) { initfuncs = register(initfuncs, "init", skip+1, f) }
func OnExit(skip int, f func()) { exitfuncs = register(exitfuncs, "init", skip+1, f) }

func RunInit() { runinits(initfuncs) }
func RunExit() { runexits(exitfuncs) }
func RunExit() { tryrunexit() }

func WaitExit() { <-exitedch }

func tryrunexit() {
if atomic.CompareAndSwapUint32(&exitednum, 0, 1) {
runexits(exitfuncs)
close(exitedch)
}
}

type function struct {
Func func()
Expand All @@ -40,12 +53,7 @@ type function struct {
}

func (f function) runinit() { f.print("init"); f.Func() }
func (f function) runexit() { defer f.recover(); f.print("exit"); f.Func() }
func (f function) recover() {
if r := recover(); r != nil {
slog.Error("exit func panics", "file", f.File, "line", f.Line, "panic", r)
}
}
func (f function) runexit() { f.print("exit"); f.Func() }

func (f function) print(ftype string) {
if DEBUG {
Expand All @@ -61,10 +69,19 @@ func runinits(funcs []function) {

func runexits(funcs []function) {
for _len := len(funcs) - 1; _len >= 0; _len-- {
funcs[_len].runexit()
saferun(funcs[_len].runexit)
}
}

func saferun(f func()) {
defer func() {
if r := recover(); r != nil {
slog.Error("wrap a panic", "panic", r)
}
}()
f()
}

func register(funcs []function, ftype string, skip int, f func()) []function {
if f == nil {
panic(ftype + " function is nil")
Expand Down
6 changes: 2 additions & 4 deletions defaults_onexit.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ var (

// ExitWaitFunc is used to wait until the program exit.
//
// Default: <-ExitContext().Done()
ExitWaitFunc = NewValueWithValidation(exitwait, fValidation("ExitWait"))
// Default: assists.WaitExit
ExitWaitFunc = NewValueWithValidation(assists.WaitExit, fValidation("ExitWait"))

// ExitSignalsFunc is used to get the signals to let the program exit.
//
Expand Down Expand Up @@ -68,8 +68,6 @@ func exitSignalsFunc() []os.Signal { return exitsignals }
// to wait until the program exit.
func ExitWait() { ExitWaitFunc.Get()() }

func exitwait() { <-ExitContext().Done() }

// OnExit registers the exit function f, which is the proxy of assists.OnExit.
func OnExit(f func()) {
assists.OnExit(1, f)
Expand Down

0 comments on commit f47b5c3

Please sign in to comment.