我有以下最小的例子,由于死锁导致第一个命令行输入后退出:
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)
}
}
}
我本来希望这只是简单地接受用户输入并反复回应它。此外,我注意到如果我添加第二个通道和第二个例程,它没有任何死锁问题。那么为什么会出现这种僵局?
答案 0 :(得分:1)
无法重现问题。
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$
你的Go版本,操作系统和操作系统是什么?架构?