On Thu, Aug 19, 2021 at 4:43 PM Денис Мухортов
<muhortovdeni...@gmail.com> wrote:

> I just started practicing with channels, after writing to the channel, 
> nothing is output from there
> func main() {
>     d := make(chan int)
>     go factorial(5, d)
>      time.Sleep(3 * time.Second)
> }
>
> func factorial(n int, d chan int) {
>     fmt.Println("function starting...")
>     time.Sleep(3 * time.Second)
>     var a int = 1
>     for ; n > 0; n-- {
>         a *= n
>     }
>     d <- a // //nothing works after that
>     fmt.Println(<-d)
>     fmt.Println(a)
> }

Your main function can and probably does just return before the write
to d in factorial is performed. When the main function returns, the
process exits.

I suggest never to use time.Sleep as a synchronization mechanism. Not
even in experiments or throw away code. It may sometimes work, but it
is probably never correct. In either case, it makes reasoning about
the code hard, if not impossible, so proper synchronization is much
better for your understanding when you're "practicing with channels".

-j

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAA40n-V_i%2Bn-9DWvaLnx9x4uA4dc9SibSG6rxcLnA5ZBVqNqDg%40mail.gmail.com.

Reply via email to