需要了解goroutines

时间:2016-10-25 03:49:40

标签: go goroutine

我是Go语言编程的新手并逐步学习它 在练习时,我发现了goroutines的随机行为 如果我调用goroutine(函数睡眠时间为1秒),有时它会成功完成,有时则不会:

package main

import (
    "fmt"
    "time"
)

func t(i int) {
    fmt.Println("In func t")
    time.Sleep(1)
}

func t1(i int) {
    fmt.Println("In func t1")
    time.Sleep(1)
}

func main() {
    fmt.Println("Hello Good Morning")
    go t(1)
    t1(2)
    time.Sleep(5)
    fmt.Println("End of func main")
}

O / p 1:

  Hello Good Morning
  In func t1
  In func t
  End of func main

O / p 2:

  Hello Good Morning
  In func t1
  End of func main

有人可以解释为什么goroutine不能保证执行该goroutine函数调用。

2 个答案:

答案 0 :(得分:1)

Program execution

  

当函数main返回时,程序退出。它不等待   其他(非主要)goroutines完成。

1- main也是goroutine,你需要等待其他goroutines完成,你可以使用

time.Sleep(5 * time.Second)

等待5秒钟,在The Go Playground上尝试:

package main

import (
    "fmt"
    "time"
)

func t(i int) {
    fmt.Println("In func t")
    time.Sleep(1 * time.Second)
}

func t1(i int) {
    fmt.Println("In func t1")
    time.Sleep(1 * time.Second)
}

func main() {
    fmt.Println("Hello Good Morning")
    go t(1)
    t1(2)
    time.Sleep(5 * time.Second)
    fmt.Println("End of func main")
}

输出:

Hello Good Morning
In func t1
In func t
End of func main

请参阅文档:

// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)

2-您可以使用sync.WaitGroup等待其他goroutines,在The Go Playground上尝试:

package main

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

var w sync.WaitGroup

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

func main() {
    w.Add(1)
    go say("A")

    w.Add(1)
    say("B")

    w.Wait()
}

输出:

B
A
A
B

答案 1 :(得分:0)

两件事:

  1. 如果您从main返回而未明确等待您的 goroutine完成,不能保证它会完成之前 程序退出。
  2. time.Sleep()的参数类型为time.Duration, 单位是纳秒。因为你几乎没有拖延 总之,你的结果是随机的并不奇怪。如果你睡了 如果在main中有更长的时间,你应该看到两者 印刷线(虽然不能保证)。
  3. 如果你需要等待goroutine完成,有多种方法可以做到这一点(例如,频道和sync.WaitGroup)。

    您可能需要浏览A Tour of Go和/或查看Effective Go