package main
import (
"fmt"
"time")
func useChan(dataChan <-chan string,stopchan <-chan string){
for{
select{
case <- dataChan:
fmt.Println("data Recieved")
time.Sleep(50 * time.Millisecond)
case <- stopchan:
fmt.Println("stopping")
return
default:
continue
}
}
}
func main() {
dataChan := make(chan string)
stopchan := make(chan string)
go useChan(dataChan,stopchan)
//ready := true
for timeout := time.After(5 *time.Second); ;{
time.Sleep(10 * time.Millisecond)
select{
case dataChan <-"something":
case <-timeout:
stopchan <- "stop"
fmt.Println("breaking ")
return
default:
//fmt.Println("continue")
continue
}
}
}
Please help me
lutzhorn
(Lutz Horn)
January 22, 2019, 7:39am
2
What do you expect to happen? What happens instead? Do you get an error?
Ok , program ran but " data recieved " in the useChan function is not printing .
This is a learning exercise . There is some logical error.
I am expecting it to print "data recieved " . It is not printing. No error during running.
lutzhorn
(Lutz Horn)
January 22, 2019, 7:43am
5
Take a look at the documentation for how to use time.After
in a select
:
https://golang.org/pkg/time/#After
ok , Thank you for your response, but apparently it worked when i changed the unbuffered channel to buffered channel with size 1.
i.e
dataChan := make(chan string,1)
stopchan := make(chan string,1)
But i don’t know the reason .
Can you please explain the behavior ? . Thank you
acim
(Boban Acimovic)
January 22, 2019, 12:57pm
7
Try to remove both default cases from select blocks. And keep unbuffered channel.
OMG , it worked .
My explanation for it , please tell me if i am right or wrong.
Non buffered channel write are blocking unless there is some goroutine reading from it. Since “case selection” in Select statement is random if more than one case is true, it was selecting default case. But still , i don’t get why it was not reading from the “dataChan” even once if the probability of selecting between default and other channel is same.
Thank you
acim
(Boban Acimovic)
January 22, 2019, 4:01pm
9
select case is pretty much random, but not completely
1 Like
system
(system)
Closed
April 22, 2019, 4:01pm
10
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.