drvntaomy06331839 2012-10-22 16:14
浏览 35
已采纳

单通道和选择语句死锁

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?

  • 写回答

1条回答 默认 最新

  • drccfl9407 2012-10-22 16:30
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?