github.com/metacubex/quic-go@v0.44.1-0.20240520163451-20b689a59136/internal/utils/afterfunc_go120.go (about)

     1  //go:build !go1.21
     2  
     3  package utils
     4  
     5  import (
     6  	"context"
     7  	"sync"
     8  )
     9  
    10  func AfterFunc(ctx context.Context, f func()) (stop func() bool) {
    11  	stopc := make(chan struct{}, 1)
    12  	donec := make(chan struct{})
    13  	go func() {
    14  		select {
    15  		case <-ctx.Done():
    16  			f()
    17  		case <-stopc:
    18  		}
    19  		close(donec)
    20  	}()
    21  	once := sync.Once{}
    22  	return func() bool {
    23  		stopped := false
    24  		once.Do(func() {
    25  			stopped = true
    26  			select {
    27  			case stopc <- struct{}{}:
    28  			default:
    29  			}
    30  			<-donec
    31  		})
    32  		return stopped
    33  	}
    34  }