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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题