dongtan7998 2019-03-27 08:23
浏览 91
已采纳

试图了解golang chan导致崩溃或执行其他操作

The following is a example from https://golang.org/ref/mem:

var c = make(chan int)
var a string

func f() {
    a = "hello, world"
    <-c
}
func main() {
    go f()
    c <- 0
    print(a)
}

is also guaranteed to print "hello, world". The write to a happens before the receive on c, which happens before the corresponding send on c completes, which happens before the print.

If the channel were buffered (e.g., c = make(chan int, 1)) then the program would not be guaranteed to print "hello, world". (It might print the empty string, crash, or do something else.)

I understand that It might print the empty string, but not for crash or do something else, when will crash happen? And when will it do something else ?

  • 写回答

1条回答 默认 最新

  • duanqin2026 2019-03-27 08:36
    关注

    A string in Go is a read only slice of bytes. Slice consists of length an pointer. Let's assume that we first set length to a large value and then change the pointer. The other go routine may first read new length and old pointer. Then it tries to read over the end of the previous string. It either read some garbage or is stopped by operating system and crashes.

    The order of operations does not matter really, if you set pointer firsts it may point to memory area too short for the current length.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记