douyu2817 2015-08-12 22:23
浏览 50
已采纳

Golang / Gopher方式来操纵不同渠道中的数据?

New to go and to make sure Im on the right page with channels + concurrency I have a struct

type Playlist struct {
  playList   []*Song
  updateList chan *Song
}

I have 2 functions that manipulate the data in separate go routines.

First one is to append data to the playlist whenever a pointer to a song is sent on the channel:

  func (p *Playlist) continuousUpdate() {
    go func (){
      for newSong := range p.updateList {
        p.playlist = append(p.playlist, newSong)
      }
    }()
  }

And the second one, every 24 hours a timer will tick, thus resetting the playlist to an empty slice.

func (p *Playlist) controlCurrentPlayList(c <-chan time.Time) {
  go func(){
    for {
      <-c
      p.playlist = make([]*Song, 0)
      log.Println("Current playlist has reset")
    }
  }()
}

Do two separate channels handle the synchronization of the data? Or could I very easily run into a race condition?

Ran go build -race and no errors appeared.

  • 写回答

1条回答 默认 最新

  • dpjs2005 2015-08-12 23:07
    关注

    Because the field playlist is accessed from two goroutines with no synchronization, there is a race.

    The race detector detects races at runtime, not build time. This race will not be detected until the 24 hour reset timer ticks.

    The race can be eliminated by combining the two goroutines using a select statement:

    for {
        select {
        case newSong := <-p.updateList:
            p.playlist = append(p.playlist, newSong)
        case <-c:
            p.playlist = make([]*Song, 0)
            log.Println("Current playlist has reset")
        }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度