github.com/grailbio/base@v0.0.11/shutdown/shutdown.go (about) 1 // Copyright 2019 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache 2.0 3 // license that can be found in the LICENSE file. 4 5 // Package shutdown implements a global process shutdown mechanism. 6 // It is used by package github.com/grailbio/base/grail to perform 7 // graceful shutdown of software components. It is a separate package 8 // in order to avoid circular dependencies. 9 package shutdown 10 11 import "sync" 12 13 // Func is the type of function run on shutdowns. 14 type Func func() 15 16 var ( 17 mu sync.Mutex 18 funcs []Func 19 ) 20 21 // Register registers a function to be run in the Init shutdown 22 // callback. The callbacks will run in the reverse order of 23 // registration. 24 25 func Register(f Func) { 26 mu.Lock() 27 funcs = append(funcs, f) 28 mu.Unlock() 29 } 30 31 // Run run callbacks added by Register. This function is not for 32 // general use. 33 func Run() { 34 mu.Lock() 35 fns := funcs 36 funcs = nil 37 mu.Unlock() 38 for i := len(fns) - 1; i >= 0; i-- { 39 fns[i]() 40 } 41 }