dtpk04526211 2013-09-28 19:23
浏览 17
已采纳

在此示例中,如何使用Go例程?

I have the following code snippet. I create a channel that takes 15 filenames at most from a given directory. I thought that I could create goroutines where one produces entries on a channel, and another consumes them. The consumer should print things taken from the channel.

My program executes without printing and I suspect that this is because the consumer routine is sleeping - isn't a new go routine started for each iteration of the for-loop? Shouldn't there eventually be something to print from the channel?

func (u* uniprot) produce(n string) {
    u.namesInDir <- n
}   

func (u* uniprot) consume() {
    fmt.println(<-u.namesInDir)
}       

func (u* uniprot) readFilenames(dirname string) {
    u.namesInDir = make(chan string, 15)
    dir, err := os.Open(dirname)
    errorCheck(err) 
    names, err := dir.Readdirnames(0)
    errorCheck(err)
    for _, n := range names {
        go u.produce(n)
        go u.consume()
    }
}
  • 写回答

1条回答 默认 最新

  • dongzhenbi8919 2013-09-28 19:31
    关注

    You need to wait for the go routines to finish.

    To see the problem put a time.Sleep at the end of the for loop.

    To fix properly use a sync.WaitGroup

    Here is an example of how it might work (untested)

    import "sync"
    
    func (u *uniprot) produce(n string, wg *sync.WaitGroup) {
        defer wg.Done()
        u.namesInDir <- n
    }
    
    func (u *uniprot) consume(wg *sync.WaitGroup) {
        defer wg.Done()
        fmt.println(<-u.namesInDir)
    }
    
    func (u *uniprot) readFilenames(dirname string) {
        u.namesInDir = make(chan string, 15)
        dir, err := os.Open(dirname)
        errorCheck(err)
        names, err := dir.Readdirnames(0)
        errorCheck(err)
        wg := new(sync.WaitGroup)
        for _, n := range names {
            wg.Add(2)
            go u.produce(n, wg)
            go u.consume(wg)
        }
        wg.Wait()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止