On Sun, Aug 06, 2017 at 12:53:08AM -0700, desaiabhi...@gmail.com wrote:

> Can you please help with below code to get output at specific cutoff time 
> and exit
[...]
>     c1 := make(chan string)
>     
>     go func() { //Sending data after certain time
>   
>         c1 <- "result 1"
> 
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 1 sec"
> 
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 2 sec"
> 
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 3 sec"
> 
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 4 sec"
> 
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 5 sec"
>     }()
> 
>     select {
>         case <-time.After(time.Second * 4): { //cut off 4s and return the 
> value
>             res := <-c1                    
>             fmt.Println(res)  // expecting result "result 2 afer 3 sec" but 
> returning "result 1"
>         }
>     }
> }

You have created a channel of capacity 0, which means that as soon as
some goroutine sends to the channel it blocks until another goroutine
reads from it.  What's more, any other goroutines which attempt to send
to that channel while the first goroutine is blocked waiting for the
value it's sending to be received, gets blocked, too.

So, in your example the goroutine which sends gets blocked in

  c1 <- "result 1"

and is suspended by the scheduler.

The main goroutine which performs select waits for the timer to fire and
then reads from c1 hereby unblocking the background goroutine and
allowing its send operation to proceed.

After that the background goroutine continues to work and then at some
indeterminate point gets reaped by the Go runtime which kills all the
active goroutine when the goroutine running main() exits.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to