dongnaigu2052 2016-10-19 14:10
浏览 48
已采纳

如何使用通道安全地同步Golang中的数据

Below is an example of how to use mutex lock in order to safely access data. My question is how would I go about doing the same with the use of CSP( Communication sequential Processes) instead of using mutex lock´s and unlock´s?

type Stack struct {
  top    *Element
  size   int
  sync.Mutex
}

func (ss *Stack) Len() int {
  ss.Lock()
  size := ss.size
  ss.Unlock()
  return size

}

func (ss *Stack) Push(value interface{}) {
  ss.Lock()
  ss.top = &Element{value, ss.top}
  ss.size++
  ss.Unlock()
}

func (ss *SafeStack) Pop() (value interface{}) {
  ss.Lock()
  size := ss.size
  ss.Unlock()
  if size > 0 {
    ss.Lock()
    value, ss.top = ss.top.value, ss.top.next
    ss.size--
    ss.Unlock()
    return
  }

  return nil
}
  • 写回答

1条回答 默认 最新

  • duanlian1978 2016-10-19 20:59
    关注

    If you actually were to look at how Go implements channels, you'd essentially see a mutex around an array with some additional thread handling to block execution until the value is passed through. A channel's job is to move data from one spot in memory to another with ease. Therefore where you have locks and unlocks, you'd have things like this example:

    func example() {
        resChan := make(int chan)
        go func(){
            resChan <- 1
        }()
        go func(){
            res := <-resChan
        }
    }
    

    So in the example, the first goroutine is blocked after sending the value until the second goroutine reads from the channel.

    To do this in Go with mutexes, one would use sync.WaitGroup which will add one to the group on setting the value, then release it from the group and the second goroutine will lock and then unlock the value.

    The oddities in your example are 1 no goroutines, so it's all happening in a single main goroutine and the locks are being used more traditionally (as in c thread like) so channels won't really accomplish anything. The example you have would be considered an anti-pattern, like the golang proverb says "Don't communicate by sharing memory, share memory by communicating."

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

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题