gitee.com/quant1x/gox@v1.21.2/coroutine/context.go (about)

     1  package coroutine
     2  
     3  import (
     4  	"context"
     5  	"gitee.com/quant1x/gox/logger"
     6  	"gitee.com/quant1x/gox/signal"
     7  	"sync"
     8  )
     9  
    10  var (
    11  	globalOnce    sync.Once
    12  	globalContext context.Context    = nil
    13  	globalCancel  context.CancelFunc = nil
    14  )
    15  
    16  func initContext() {
    17  	globalContext, globalCancel = context.WithCancel(context.Background())
    18  }
    19  
    20  // Context 获取全局顶层context
    21  func Context() context.Context {
    22  	globalOnce.Do(initContext)
    23  	return globalContext
    24  }
    25  
    26  // Shutdown 关闭应用程序, 通知所有协程退出
    27  func Shutdown() {
    28  	globalOnce.Do(initContext)
    29  	if globalCancel != nil {
    30  		globalCancel()
    31  	}
    32  }
    33  
    34  func GetContextWithCancel() (context.Context, context.CancelFunc) {
    35  	globalOnce.Do(initContext)
    36  	ctx, cancel := context.WithCancel(globalContext)
    37  	return ctx, cancel
    38  }
    39  
    40  // WaitForShutdown 阻塞等待关闭信号
    41  func WaitForShutdown() {
    42  	globalOnce.Do(initContext)
    43  	interrupt := signal.Notify()
    44  	select {
    45  	case <-globalContext.Done():
    46  		logger.Infof("application shutdown...")
    47  		globalCancel()
    48  		break
    49  	case sig := <-interrupt:
    50  		logger.Infof("interrupt: %s", sig.String())
    51  		globalCancel()
    52  		break
    53  	}
    54  }