gpt4 book ai didi

golang,为什么永远不会调用 goroutine 函数

转载 作者:IT王子 更新时间:2023-10-29 01:59:29 25 4
gpt4 key购买 nike

package main

import (
"fmt"
//"runtime"
)

func say(s string) {
for i := 0; i < 5; i++ {
//runtime.Gosched()
fmt.Println(s)
}
}

func main() {
go say("world") // create a new goroutine
say("hello") // current goroutine
}

为什么结果是:

hello
hello
hello
hello
hello

为什么没有world

答案:(已编辑:)如果我这样做,现在就好了:

package main

import (
"fmt"
"runtime"
)

func say(s string) {
for i := 0; i < 5; i++ {
//runtime.Gosched()
fmt.Println(s)
}
}

func main() {
go say("world") // create a new goroutine
runtime.Gosched()

say("hello") // current goroutine
}

最佳答案

您只是遇到了时间问题,因为您没有“协调”您的 go 例程。处理此问题的常用方法是使用等待 guard 。我不时看到的另一个选项是使用 channel 和阻塞选择。等待守卫的实现看起来像这样;

func main() {
wg := sync.WaitGroup{}
wg.Add(1)
go say("world") // create a new goroutine

wg.Add(1)
say("hello") // current goroutine
wg.Wait()
}

虽然 channel 选项(在此示例中实际上并不有趣或有用)更像是这样;

 func main() {
done := make(chan bool)
go say("world", done) // create a new goroutine

say("hello", done) // current goroutine

select {
case fin := <- done:
//on finished
return
}
}

func say(s string, chan bool) {
for i := 0; i < 5; i++ {
fmt.Println(s)
}
done <- true
}

虽然在上面的例子中,第一次调用完成将允许程序完成执行。为确保两者都完成,您必须将不同的 channel 传递给每个 channel 并在两者上进行阻塞读取。当您的 go 例程正在执行实际工作并且您希望将数据从它们中聚合数据或需要更复杂的协调(例如根据先前的结果生成新的 goroutines 等)时,这更像是一种模式。

关于golang,为什么永远不会调用 goroutine 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com