First goroutine example, weird results

This example is taken from tour.golang.org/#63

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

Output

hello
world
hello
world
hello
world
hello
world
hello

Why worldis it printed only 4once instead 5?


Edit: The answer can be specified from the golang specification :

Program execution begins by initializing the main package, and then calling the main function. When the main function returns, the program exits. He does not wait until other (not main) guests are full.

+3
source share
3 answers

, goroutines . go say("world"). , .

+5

- sync.WaitGroup

package main

import (
    "fmt"
    "sync"
    "time"
)

func say(s string, wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    wg := new(sync.WaitGroup)
    wg.Add(2)
    go say("world", wg)
    go say("hello", wg)
    wg.Wait()
    fmt.Println("All done")
}
+4

Because the gorouting call ends before the second one you spawned. This causes the second to be disabled. To illustrate this, slightly modify your code:

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Print(i)
        fmt.Println(":"+s)
    }
}

func main() {
    go say("world")
    say("hello")
}

Try inserting "wait" or sleep at the end of the main function.

+2
source

Source: https://habr.com/ru/post/1672113/


All Articles