Search code examples
goconcurrencyvolatile

Golang visibility or CPU thread cache issue


1) How does golang solve visibility issue?

2) Is there any issues with below code?

package main

type Service struct {
    stop bool
}

func (s *Service) Run() {
    for !s.stop {
        //Some logic
    }
}

func (s *Service) Stop() {
    s.stop = true
}

func main() {
    s := &Service{}
    go s.Run()
    //Some logic
    s.Stop()
}

Solution

  • I recommend to use context.WithCancel to stop goroutines in this case.