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:
counter
goroutine
that keeps updating this counter every one 1 secondgoroutine
that keeps printing this counter every two secondsPlayground 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?
One way may be to send message to 2nd gorutine when it comes time to print.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Start");
counter := 0
printChannel := make( chan int)
done := make(chan struct{} )
go func(done <-chan struct{}, printChannel chan<- int ){
timer := time.NewTicker(time.Second)
bDone := false;
for !bDone {
select {
case <-timer.C:
counter++
if counter%2 == 0 {
printChannel <- counter
}
case <-done:
bDone=true
}
}
}(done, printChannel)
go func(done <-chan struct{}, printChannel <-chan int ){
bDone:=false
for !bDone{
select {
case n := <-printChannel:
fmt.Print(n, " ");
case <-done:
bDone=true
}
}
}(done,printChannel)
//whatever logic to stop
go func() {
<- time.After(21*time.Second)
done <- struct{}{}
}()
<-done
fmt.Println("\nEnd");
}
Note that here there is 3rd gorutine just to finish the example
Output:
Start
2 4 6 8 10 12 14 16 18 20
End
To improve it, you can do it without bDone variable, you can stop Ticker and add appropriate message when gorutine exists.
Or you may want to test 'break' with label to exit for loop.
You can test effect when you use close(done) channel instead of sending message to it.
Also, if you are ready to relax read/write order, you can remove printChannel and make 2nd gorutine use another ticker that pings every 2 seconds.