Skip to content

Latest commit

 

History

History
69 lines (57 loc) · 1.82 KB

example_7.md

File metadata and controls

69 lines (57 loc) · 1.82 KB

7. Let's handle shutdown gracefully, for real this time!

Basic counter | Race detection | WaitGroup | Mutex counter | Atomic counter | Channels | Signals

package concurrency

// NonStoppingGoRoutineCorrectShutdown yes?
func NonStoppingGoRoutineCorrectShutdown() (int, bool) {
	atomicCounter := counter.NewAtomicCounter()
	wg := sync.WaitGroup{}
	gracefulShutdown := false

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	wg.Add(1)
	go func() {
		defer wg.Done()
		defer func() { gracefulShutdown = true }()

		for {
			select {
			case <-sigs:
				return
			default:
				inlinePrint(atomicCounter.Inc())
			}

		}
	}()

	wg.Wait()
	return atomicCounter.Count(), gracefulShutdown
}
  go test ../../internal/goroutine -v -count=1 -run="NonStoppingGoRoutineCorrectShutdown$" 
  go test ../../internal/goroutine -v -count=1 -run="NonStoppingGoRoutineCorrectShutdown$" -race 
Results?
Correct result? ? ?
No race conditions? ?
Error handling and gracefully shutdown? ?

Solution