doujia1871 2014-01-04 17:25
浏览 390
已采纳

Golang封装块变量的线程安全吗?

According to the Go spec:

"The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block."

Are package block variables thread safe? E.G. If I have a package block variable to store the current user for a web app:

var CurrentUser *string

Request 1 comes in: Set CurrentUser to "John" Request 2 comes in: Set CurrentUser to "Fred"

In Request 1 what is the value of CurrentUser?

  • 写回答

1条回答 默认 最新

  • dq8081 2014-01-04 17:59
    关注

    No, package variables are not thread safe.

    In your example, CurrentUser could change from "John" to "Fred" at any time—although the goroutine handling Request 1 is not guaranteed to see the change.

    So you need to use a local variable to store any data that is different for different goroutines.

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

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动