golang的管道通信在作为独立函数时有效,但作为主函数的一部分时无效。

huangapple go评论137阅读模式
英文:

golang pipelining channels - works as a separate function, but doesn't work as a part of main function

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对Go语言还不熟悉,目前我正在尝试理解通道同步的工作原理。我正在解决一个测试任务,需要我从通道中构建一个流水线。我编写了两个类似的解决方案,但其中一个出现了未知原因(对我来说)导致无法工作。

这个不起作用(go协程直接从函数中启动):

https://play.golang.org/p/EHceKjZZ-G

这个起作用(go协程从一个单独的函数中启动):

https://play.golang.org/p/QysTAVxbVc

我完全迷失了,我看不出两者之间的区别,也无法理解为什么第一个例子不起作用。有人有任何想法吗?

英文:

I'm new to go, and at the moment I'm trying to understand how channel synchronisation works. I'm solving a test task that requires me to build a pipeline from channels. I wrote two similar solutions, but one of this doesn't work for an unknown reason (for me).

This doesn't work (the go-routines are started from the function directly):

https://play.golang.org/p/EHceKjZZ-G

This works (the go-routines are started from a separate function):

https://play.golang.org/p/QysTAVxbVc

I'm totally lost, I don't see the difference and can't understand why the first example doesn't work. Does any one have any idea?

答案1

得分: 2

你正在goroutine中使用一个捕获变量fn,在迭代过程中该变量将被覆盖。所有goroutine看到的是funcs中的最新作业。请将你的Pipe函数代码更改为以下内容:

for _, fn := range funcs {
	out = make(chan interface{})
	wg.Add(1)
	go func(f job, inx, outx chan interface{}) {
		f(inx, outx)
		close(outx)
		wg.Done()
	}(fn, in, out)

	in = out
}

这是在Go语言中的一个常见错误之一。

英文:

You're using a capture variable fn across goroutine, in which the variable will be overridden during iteration. What is seen by all goroutines is the latest job in the funcs. Change your code in Pipe function to the following:

for _, fn := range funcs {
	out = make(chan interface{})
	wg.Add(1)
	go func(f job, inx, outx chan interface{}) {
		f(inx, outx)
		close(outx)
		wg.Done()
	}(fn, in, out)

	in = out
}

It's one of common mistake in golang.

huangapple
  • 本文由 发表于 2017年6月3日 15:44:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/44341662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定