I have created two go routines sender and receiver, sender will continuous get the data from the user(keyboard) and write to stream, receiver will independently get the value from stream print it to the screen. Both are concurrent using go routine
At some point of time receiver failed and close the connection as well as exit the receiver go routine, but sender go routine which waiting for user input(i/o operation) will not be closed. How to exit all the go routines in this scenario?
Below is the piece of sample code for this scenario.
package main
import (
"fmt"
"time"
)
var stop bool = false
func sender() {
str := ""
for !stop {
fmt.Scanf("%s", &str)
fmt.Println("Entered :", str)
}
fmt.Println("Closing sender goroutine")
}
func receiver() {
i := 0
for !stop {
i++
if i > 5 {
stop = true
}
time.Sleep(1 * time.Second)
}
fmt.Println("Closing receiver goroutine")
}
func main() {
go sender()
go receiver()
/* Wait for goroutines to finish */
for !stop {
time.Sleep(1 * time.Millisecond)
}
time.Sleep(1 * time.Second)
panic("Display stack")
}
Above code sender will wait for user input after 5 loop receiver will exit the receiver go routine. I expect when receiver close, go routine which waiting on i/o has to be closed.
Kindly help me on this question.