I am in the process of learning go, and I am having trouble with goroutines
. Here is my code
package main
import (
"fmt"
"sync"
"time"
)
var counter = 0
var wg = sync.WaitGroup{}
func main() {
ticker := time.NewTicker(time.Second)
go func() {
for range ticker.C {
// wg.Add(1)
// defer wg.Done()
counter++
fmt.Println(counter)
//wg.Done()
}
}()
ticker2 := time.NewTicker(time.Second * 2)
wg.Add(1)
go func() {
for range ticker2.C {
//defer wg.Done()
fmt.Println(counter)
}
}()
wg.Wait()
}
Basically, I would like to have:
- a global variable called
counter
- one
goroutine
that keeps updating this counter every one 1 second - another
goroutine
that keeps printing this counter every two seconds
Playground is here
I tried to play with WaitGroup
but I did not manage to have this working.
With this level of code, I have the following warning:
WARNING: DATA RACE
Read at 0x0000011d8318 by goroutine 8:
runtime.convT2E64()
Another question is this thread safe? I mean, can I safely use counter in the main method outside of the two groroutines?