mihomo/common/contextutils/afterfunc_compact.go
wwqgtxx bfd06ebad0
Some checks failed
Trigger CMFA Update / trigger-CMFA-update (push) Failing after 1s
chore: rebuild SetupContextForConn with context.AfterFunc
2025-04-10 01:29:55 +08:00

32 lines
487 B
Go

package contextutils
import (
"context"
"sync"
)
func afterFunc(ctx context.Context, f func()) (stop func() bool) {
stopc := make(chan struct{})
once := sync.Once{} // either starts running f or stops f from running
if ctx.Done() != nil {
go func() {
select {
case <-ctx.Done():
once.Do(func() {
go f()
})
case <-stopc:
}
}()
}
return func() bool {
stopped := false
once.Do(func() {
stopped = true
close(stopc)
})
return stopped
}
}