2014-01-04 17:25



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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dq8081 dq8081 7年前

    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.

    点赞 评论 复制链接分享