doucan9079 2016-06-06 11:07
浏览 40
已采纳

在Go1.5中执行GC后,此代码会引起恐慌吗?

package main

import "time"

var x = []string{}

func main() {
    go func() {
        for {
            y := x
            y = append(y, "aa")
        }
    }()
    go func() {
        for {
           x = []string{"123"}
        }
    }()
    for {
        time.Sleep(1)
    }
}

guess like when x (for example, the address of 123) is not really assigned to y, and x is assigned to a new address like 124. and just this time gc happened, would the address of 123 be recycled and cause a panic?

  • 写回答

2条回答 默认 最新

  • drmqzb5063 2016-06-06 12:05
    关注

    No. First of all, x has a global scope. So GC won't happen until a new value with new address is assign to it.

    Now when a new value is assign, two things can happen:

    1. Goroutine assigning y to x happens. It get assign to y. Then no GC will happen.
    2. It will get new value with new address before first step happens.

    I don't know what you are trying to do. But there's no panic even if goroutine runs simultaneously. X always has a value.

    Since you asked that whether assignment is atomic: No normal assignment is atomic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘