英文:
Single channel and select statement deadlock
问题
我有一个最小化的示例,由于死锁,它在第一个命令行输入后就退出了:
package main
import "fmt"
import "os"
func main() {
channel1 := make(chan string)
go func() {
var str string
for {
fmt.Fscanln(os.Stdin, &str)
channel1 <- str
}
}()
for {
select {
case str := <-channel1:
fmt.Printf("Channel1 said: %v\n", str)
}
}
}
我本来期望它只是接受用户输入并不断地回显。另外,我注意到如果我添加第二个通道和第二个go例程,它就没有任何死锁问题。那么为什么会发生死锁呢?
英文:
I have the following minimal example that bails out after the first command line input due to deadlock:
package main
import "fmt"
import "os"
func main() {
channel1 := make(chan string)
go func() {
var str string
for {
fmt.Fscanln(os.Stdin, &str)
channel1 <- str
}
}()
for {
select {
case str := <-channel1:
fmt.Printf("Channel1 said: %v\n", str)
}
}
}
I would have expected this to simply just take user input and echo it over and over again. Also, I did notice that if I add a second channel and a second go routine that it doesn't have any deadlock issues. So why does this deadlock?
答案1
得分: 1
go version go1.0.3
Linux fsc-r630 3.2.0-32-generic #51-Ubuntu SMP Wed Sep 26 21:33:09 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
英文:
Cannot reproduce the problem.
jnml@fsc-r630:~/src/tmp/SO/13015469$ cat main.go
package main
import (
"fmt"
"os"
)
func main() {
channel1 := make(chan string)
go func() {
var str string
for {
fmt.Fscanln(os.Stdin, &str)
channel1 <- str
}
}()
for {
select {
case str := <-channel1:
fmt.Printf("Channel1 said: %v\n", str)
}
}
}
jnml@fsc-r630:~/src/tmp/SO/13015469$ go run main.go
foo
Channel1 said: foo
bar
Channel1 said: bar
baz
Channel1 said: baz
^Cjnml@fsc-r630:~/src/tmp/SO/13015469$ go build main.go && ./main
foo
Channel1 said: foo
bar
Channel1 said: bar
baz
Channel1 said: baz
^Cjnml@fsc-r630:~/src/tmp/SO/13015469$ go version
go version go1.0.3
jnml@fsc-r630:~/src/tmp/SO/13015469$ uname -a
Linux fsc-r630 3.2.0-32-generic #51-Ubuntu SMP Wed Sep 26 21:33:09 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
jnml@fsc-r630:~/src/tmp/SO/13015469$
What's your Go version, OS & architecture?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论