Use a mutex to read the current value of a variable. The mutex approach is simpler than communicating by channel.
type sensor struct {
mu sync.Mutex
value int
}
func (s *sensor) run() {
for {
s.mu.Lock()
s.value += 1
s.mu.Unlock()
time.Sleep(100 * time.Millisecond)
}
}
func (s *sensor) get() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.value
}
Call like this:
temperature := &sensor{value: 42}
go temperature.run()
log.Println("EARLY TEMP READING:", temperature.get())
time.Sleep(3 * time.Second) //LET SOME ARBITRARY TIME PASS
log.Println("LATER TEMP READING:", temperature.get())