英文:
When next goroutine is executed?
问题
我正在查看来自https://blog.golang.org/pipelines的示例:
func main() {
in := gen(2, 3)
// 将sq工作分布到两个同时从in中读取的goroutine中。
c1 := sq(in)
// 这行代码`c2 := sq(in)`何时执行?`in`中有什么?
c2 := sq(in)
// 从c1和c2中消费合并的输出。
for n := range merge(c1, c2) {
fmt.Println(n) // 4然后9,或者9然后4
}
}
c2 := sq(in)
何时运行?据我理解,它不是在前一行完成后执行,而是立即执行,因为它是一个goroutine。
c2
会接收到在c1
接收到的消息之后的下一个传入消息吗?
英文:
I am looking at the example from https://blog.golang.org/pipelines:
func main() {
in := gen(2, 3)
// Distribute the sq work across two goroutines that both read from in.
c1 := sq(in)
// When does this line below execute and what is in `in`?
c2 := sq(in)
// Consume the merged output from c1 and c2.
for n := range merge(c1, c2) {
fmt.Println(n) // 4 then 9, or 9 then 4
}
}
When does c2 := sq(in)
run? As what I understand, it executes not when previous line finishes, but instantly as that is a goroutine.
Will c2
receive the next incoming message that is after coming after the message that is received by c1
?
答案1
得分: 0
你的代码没有使用goroutines,要使用goroutines,你应该像这样做:
q := make(chan type)
go sq(in, q)
go sq(in, q)
for elem := range q {
fmt.Println(elem)
}
并且sq
函数必须通过一个通道返回值:
func sq(in type, q chan type) {
// ...
q <- valueFromIn
// ...
}
此外,你可以使用WaitGroup来等待goroutines完成。
英文:
Your code does not use goroutines, in order to use go routines you should do something like this:
q := make(chan type)
go sq(in, q)
go sq(in, q)
for elem := range q {
fmt.Println(elem)
}
and sq must return the value through a channel
func sq(in type, q chan type) {
...
q <- valueFromIn
...
}
Also you can use WaitGroup to wait for goroutines to finish.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论