function with goroutine returned will kill its goroutine?

1,179 views
Skip to first unread message

Kenshin Wang

unread,
Jul 4, 2016, 11:08:38 AM7/4/16
to golang-nuts

package main

import "fmt"

func main() {
ca := createCounter(2)
cb := createCounter(102)
for i := 0; i < 5; i++ {
a := <-ca
fmt.Printf("A %d \nB %d \n", a, <-cb)
}

}

func createCounter(start int) chan int {
next := make(chan int)
go func(i int) {
for {
next <- i
i++
}
}(start)
return next
}


the output is:
A 2
B 102
A 3
B 103
A 4
B 104
A 5
B 105
A 6
B 106
 
could anyone can explain why the output is this?
especially, i don't understand when the goroutine will be destroyed,i think when the createCounter() function returned the goroutine will be killed, but it seems not ...
thank you






 

Jan Mercl

unread,
Jul 4, 2016, 11:13:39 AM7/4/16
to Kenshin Wang, golang-nuts

On Mon, Jul 4, 2016 at 5:08 PM Kenshin Wang <kenshi...@gmail.com> wrote:

        go func(i int) {
                for {
                        next <- i
                        i++
                }
        }(start)
> could anyone can explain why the output is this?

A goroutine dies when it returns. A goroutine with an endless loop is immortal (modulo unhandled panics).

--

-j

Christoph Berger

unread,
Jul 5, 2016, 3:29:40 PM7/5/16
to golang-nuts, kenshi...@gmail.com
In addition to that, all goroutines exit when the main function exits. In your code, this happens when i == 5. This explains the output that you get. Both goroutines are able to produce five numbers until the main loop finishes and the main function exits.

Paul Borman

unread,
Jul 6, 2016, 10:48:23 AM7/6/16
to Christoph Berger, golang-nuts, kenshi...@gmail.com
You probably should say all goroutines are terminated when main exits (or os.Exit is called or the program abnormally terminates), lest someone complain that their defer functions were not run.

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Christoph Berger

unread,
Jul 6, 2016, 4:18:21 PM7/6/16
to Paul Borman, golang-nuts, kenshi...@gmail.com
Good point, thanks. Yes, when the process exits, the goroutines end immediately without running their defer functions.
Reply all
Reply to author
Forward
0 new messages