4 回答

TA贡献1851条经验 获得超5个赞
试试这个,使用你的代码作为基础
package main
import (
"fmt"
"time"
)
func myFunc(ch chan int, done chan struct{}) {
defer close(done) // channel will be closed in the function exit phase
fmt.Println("Inside goroutine:: myFunc()")
fmt.Println(10 + <-ch) //<-- According to rule, control will be blocked here until 'ch' sends some data so that it will be received in our myFunc() go routine.
}
func main() {
fmt.Println("Start Main method")
// Creating a channel
ch := make(chan int)
done := make(chan struct{}) // signal channel
go myFunc(ch, done) //<-- This go routine started in a new thread
time.Sleep(2 * time.Second) //<--- introduced a Sleep of 2 seconds to ensure that myFunc() go routine executes before main thread
ch <- 10
<-done // waiting for function complete
fmt.Println("End Main method")
}
或者使用雅罗斯瓦夫的建议。

TA贡献1859条经验 获得超6个赞
主戈鲁廷在戈鲁廷能够打印输出之前就已存在。下面是一个实现,它确保戈鲁廷在主戈鲁丁退出之前完成。myFuncmyFunc
package main
import (
"fmt"
"sync"
"time"
)
func myFunc(ch chan int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("Inside goroutine:: myFunc()")
fmt.Println(10 + <-ch) //<-- According to rule, control will be blocked here until 'ch' sends some data so that it will be received in our myFunc() go routine.
}
func main() {
fmt.Println("Start Main method")
// Creating a channel
ch := make(chan int)
wg := sync.WaitGroup{}
wg.Add(1)
go myFunc(ch, &wg) //<-- This go routine started in a new thread
time.Sleep(2 * time.Second) //<--- introduced a Sleep of 2 seconds to ensure that myFunc() go routine executes before main thread
ch <- 10
wg.Wait()
fmt.Println("End Main method")
}
此处的通道用于同步,其工作方式与文档中的说明相同。这并不意味着从代码中的这一点开始的代码将以相同的速度执行。这只意味着如果戈鲁廷没有从频道读取,主戈鲁廷将不会继续。并将等待主戈鲁丁将数据推送到通道。发生这种情况后,两个哥律特将继续独立执行。myFuncmyFunc

TA贡献1843条经验 获得超7个赞

TA贡献1757条经验 获得超7个赞
是的,你是对的
我认为,这是因为主线程首先完成了它的执行,因此,所有其他goroutine也终止了。
如果您检查上述程序的执行情况。休眠状态是在主线程写入通道之前。现在即使哪个 goroutine() 将有 CPU 时间是完全任意的,但在上述情况下,如果休眠在逻辑之前。 将被阻止,因为 中没有数据mainexplicit sleepmyFuncch
在这里,我对上面的代码进行了轻微的更改,以便在将数据写入 Channel 后进行睡眠。它提供预期的输出,不使用 或 。mainwaitgroupquit channels
package main
import (
"fmt"
"time"
)
func myFunc(ch chan int) {
fmt.Println("Inside goroutine:: myFunc()")
fmt.Println(10 + <-ch) //<-- According to rule, control will be blocked here until 'ch' sends some data so that it will be received in our myFunc() go routine.
}
func main() {
fmt.Println("Start Main method")
// Creating a channel
ch := make(chan int)
go myFunc(ch) //<-- This go routine started in a new thread
ch <- 10
time.Sleep(2 * time.Second) //<--- introduced a Sleep of 2 seconds to ensure that myFunc() go routine executes before main thread
fmt.Println("End Main method")
}
- 4 回答
- 0 关注
- 116 浏览
添加回答
举报