Skip to content

Commit

Permalink
fix: remove the lock when executing the exit functions
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Feb 12, 2022
1 parent af853eb commit 4c48240
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions atexit.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ import (
"context"
"os"
"sort"
"sync"
"sync/atomic"
"time"
)
Expand All @@ -94,26 +93,19 @@ func (fs priofuncs) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] }

var (
executed uint32
execlock sync.Mutex
priority = int64(99)
executech = make(chan struct{})
exitfuncs = make(priofuncs, 0, 4)
ctx, cancel = context.WithCancel(context.Background())
)

func execute() (yes bool) {
if atomic.LoadUint32(&executed) == 0 {
execlock.Lock()
defer execlock.Unlock()
if yes = atomic.LoadUint32(&executed) == 0; yes {
defer atomic.StoreUint32(&executed, 1)

cancel()
for _len := len(exitfuncs) - 1; _len >= 0; _len-- {
func(f func()) { defer recover(); f() }(exitfuncs[_len].Func)
}
close(executech)
if yes = atomic.CompareAndSwapUint32(&executed, 0, 1); yes {
cancel()
for _len := len(exitfuncs) - 1; _len >= 0; _len-- {
func(f func()) { defer recover(); f() }(exitfuncs[_len].Func)
}
close(executech)
}
return
}
Expand Down

0 comments on commit 4c48240

Please sign in to comment.