【问题标题】:Is there is a data race when you send a message to channel and close it?当您向通道发送消息并关闭它时是否存在数据竞争?
【发布时间】:2014-10-24 06:08:47
【问题描述】:

我遇到了这样的数据竞争

WARNING: DATA RACE
11652 Read by goroutine 14:
11653   runtime.chansend()
11654       /usr/local/go/src/pkg/runtime/chan.c:155 +0x0
            ...
11657
11658 Previous write by goroutine 13:
11659   runtime.closechan()
11660       /usr/local/go/src/pkg/runtime/chan.c:1232 +0x0
            ...

频道有锁,为什么会出现数据竞争?

【问题讨论】:

  • 我看到两个不同的例程,一个是发送,一个是关闭。最明显的是数据竞赛。你说频道有锁是什么意思?你会显示相关代码吗?
  • 使用相同通道的不同 goroutine 不应该有数据竞争。频道已锁定其工具。
  • 您需要提供更多代码。
  • 请提供导致数据争用的代码。没有您的代码,很难回答有关您的代码的问题。

标签: go channel goroutine


【解决方案1】:

通道在关闭后被写入。即使只有一个 goroutine,你也会看到恐慌。

package main

func main() {
    c := make(chan struct{})
    close(c)
    c <- struct{}{}  // should panic!
}

你得到的是各种各样的,但是一个 goroutine 关闭,另一个 goroutine 试图在之后编写。竞争检测器正确地将其报告为数据竞争。

为什么在您的程序中关闭频道?

【讨论】:

  • 当单个 goroutine 场景没有引起恐慌时,可能会发生这种数据竞争。
猜你喜欢
  • 1970-01-01
  • 2020-04-18
  • 2018-05-22
  • 1970-01-01
  • 2017-01-05
  • 2020-09-13
  • 2017-01-08
  • 1970-01-01
  • 2021-03-10
相关资源
最近更新 更多