单通道和选择语句死锁
问题描述:
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
", 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?
答
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
", 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?