【问题标题】:How can I have two goroutines of the same function which look at each others' values?我怎样才能有两个具有相同功能的 goroutine 来查看彼此的值?
【发布时间】:2020-06-04 07:59:26
【问题描述】:

我正在尝试实现一个可以使用两个 goroutine 和不同参数调用的函数。每个人都将操纵自己的字符串,他们将通过一个通道将他们的字符串发送给彼此并比较结果。 Here 是我的尝试(Go Playground 链接):

func swap_values(str string, strChan1 chan string, strChan2 chan string, done chan bool) {
  str += "test"
  strChan1 <- str
  <-strChan2
  done <- true
}

这是死锁。对于我对该函数的两次调用,我交换了通道,因此 strChan1 是每个不同的通道。我怎样才能解决这个问题以不死锁并完成我想要的?同样,我将比较字符串并进行额外的操作,这只是获得两者的概念证明。

【问题讨论】:

    标签: multithreading go parallel-processing channel goroutine


    【解决方案1】:

    这是死锁,因为两个 goroutine 都试图写入没有人在听的通道。第一个 goroutine 尝试写入一个通道,由于第二个没有从它读取,所以它被卡在那里。第二个 goroutine 做同样的事情,所以他们都停下来,互相等待。

    处理这个问题的最简单方法是使用大小为 1 的通道,因此无需等待读取器即可继续写入。

    strChan1 := make(chan string,1)
    strChan2 := make(chan string,1)
    

    如果必须使用 0 长度的通道,则需要使用 select 来适应 goroutine 的不同排序:

    select {
      case strChan1 <- str:
         <-strChan2
      case <-strChan2:
         strChan1 <- str
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 2022-11-28
      • 2021-10-06
      • 2015-09-26
      • 1970-01-01
      • 2016-07-22
      • 2020-05-31
      相关资源
      最近更新 更多