gpt4 book ai didi

Golang/Gopher 操作不同 channel 数据的方式?

转载 作者:IT王子 更新时间:2023-10-29 02:27:51 25 4
gpt4 key购买 nike

新手去确保我在正确的页面上有 channel + 并发我有一个结构

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

我有 2 个函数在单独的 go 例程中操作数据。

第一个是在 channel 上发送指向歌曲的指针时将数据附加到播放列表:

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

第二个,计时器每 24 小时会计时一次,从而将播放列表重置为空片段。

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

是否有两个独立的 channel 处理数据的同步?或者我会很容易遇到竞争条件吗?

运行 go build -race 并且没有出现错误。

最佳答案

因为 playlist 字段是从两个没有同步的 goroutines 访问的,所以存在竞争。

竞争检测器在运行时而不是构建时检测竞争。在 24 小时重置计时器滴答作响之前,不会检测到这场比赛。

可以通过使用 select 语句组合两个 goroutine 来消除竞争:

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")
}
}

关于Golang/Gopher 操作不同 channel 数据的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com