79178812

Date: 2024-11-11 18:55:34
Score: 0.5
Natty:
Report link

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())

https://go.dev/play/p/SBKHAS6dqn9

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Mersa Dingwat