I have one array that gets modified a few times per second with one goroutine. In another function, I read a random value from the array once every few seconds. What would be the most Go-like way of approaching this problem?
In Java, for example, I would lock the array first and then read from it. I'm not sure if I could use channels for this because I don't want to wait until my other function reads before I can continue updating the array.
package main
import (
"fmt"
"math/rand"
"time"
)
const (
SliceLength = 32
)
var mySlice []int
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func writeSlice() {
for index, _ := range mySlice {
mySlice[index] = rand.Intn(100)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
mySlice = make([]int, SliceLength)
// First time just to populate it.
writeSlice()
// Write to the slice.
go func() {
for {
time.Sleep(time.Duration(randInt(10, 50)) * time.Millisecond)
writeSlice()
}
}()
// Read from slice.
for {
time.Sleep(time.Duration(randInt(1, 5)) * time.Second)
fmt.Println(mySlice[randInt(0, SliceLength)])
}
}