Golang random binary generator and signal to stop
August 15, 2019
A simple, fully functional Go code below shows that it generates random binary number in every one second.
The main routine keeps reading binary number from channel rand.
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
sigs := make(chan os.Signal, 1)
rand := make(chan int)
//registers the given channel to receive notifications of the specified signals
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
select {
case rand <- 0:
case rand <- 1:
}
select {
case sig := <-sigs:
fmt.Println("got signal:", sig)
close(rand)
return
case <-time.After(1 * time.Second):
}
}
}()
for r := range rand {
fmt.Println("random binary", r)
}
}In the first select statement of the goroutine, channel rand is fed either 0 or 1 at random(whichever is fed first to rand). In the second select, either output from signal channel or timeout channel is picked.
In case that there is output from signal channel before timeout in the second select statement of the goroutine,
it closes the rand channel, because main routine would keep reading this channel otherwise.
Note that there is return instead of break after closing the rand channel.
It wouldn’t work if it was break, because it would break only select, not the for loop, and in the next iteration of the for loop, it would try to send 0 or 1 to the channel rand which had already been closed.
That would put the program into panic.
Written by Sangche. Github