douyun1860 2018-07-28 23:51
浏览 29
已采纳

在控制台上不打印接收通道值

I am a learner to GoLang and was trying to experiment and learn about Sync package and chan concept.

Follwoing is the code I am running and expecting to print Receiving Channel Value on console, but the value is not getting printed, it print the values sometimes but not always.

If I range through the chan without putting it into the go routine then its printing all the channel values but failing with an error "fatal error: all goroutines are asleep - deadlock!"

I tried synchronizing the channel reading using channel "done", but in that case it again started failing with same error. I also tried waitGroup API as well which you can see in my code (commented), but that also didn't worked for me.

Thanks for the help

Source Code:

package main

import (
    "fmt"
    "sync"
)

type safeOperation struct {
    i int
    sync.Mutex
}

var wg sync.WaitGroup

func main() {
    so := new(safeOperation)
    ch := make(chan int)
    //done := make(chan bool)
    for i := 0; i < 5; i++ {
        go so.Increment(ch)
        go so.Decrement(ch)
    }

    go func() {
        //wg.Add(1)
        for c := range ch {
            fmt.Println("Receiving Channel Value: ", c)
        }
        //wg.Done()
        //done <- true
    }()
    //wg.Wait()
    //<-done
    fmt.Println("Value: ", so.GetValue())
    fmt.Println("Main method finished")
}

func (so *safeOperation) Increment(ch chan int) {
    //so.Lock()
    //defer wg.Done()
    so.i++
    ch <- so.i
    //so.Unlock()
}

func (so *safeOperation) Decrement(ch chan int) {
    //so.Lock()
    //defer wg.Done()
    so.i--
    ch <- so.i
    //so.Unlock()
}

func (so *safeOperation) GetValue() int {
    so.Lock()
    v := so.i
    so.Unlock()
    return v
}

Output: Value: 1 Main method finished

  • 写回答

1条回答 默认 最新

  • douzhanjia0773 2018-07-29 00:11
    关注

    A good pattern for using WaitGroup is to call Add() before you send to the channel or use the go keyword, and call Done() after receiving from the channel. This way you can be sure that Add() is always called on-time, regardless of whether sending on the channel blocks.

    I have changed your example code to do this:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    type safeOperation struct {
        i int
        sync.Mutex
    }
    
    var wg sync.WaitGroup
    
    func main() {
        so := new(safeOperation)
        ch := make(chan int)
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go so.Increment(ch)
            wg.Add(1)
            go so.Decrement(ch)
        }
    
        go func() {
            for c := range ch {
                fmt.Println("Receiving Channel Value: ", c)
                wg.Done()
            }
        }()
        wg.Wait()
        //<-done
        fmt.Println("Value: ", so.GetValue())
        fmt.Println("Main method finished")
    }
    
    func (so *safeOperation) Increment(ch chan int) {
        so.i++
        ch <- so.i
    }
    
    func (so *safeOperation) Decrement(ch chan int) {
        so.i--
        ch <- so.i
    }
    
    func (so *safeOperation) GetValue() int {
        so.Lock()
        v := so.i
        so.Unlock()
        return v
    }
    

    Go playground link

    Of course you also want to protect safeOperation.i with a mutex (or its value will be unpredictable), but this is all that is necessary to get the desired output.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题