2018-06-15 09:41 阅读 36

在程序包级别声明互斥量变量是一种好习惯吗? [关闭]

In one package, i declare some variable and also a mutex variable. I want to use it to lock or unlock get/set of package level variables.

var mutex sync.Mutex
var tplPath = ""

func Prepare(c *gin.Context) {
    tplPath = "abc"

Can it be consider as good practice while using mutex can prevent race condition of get/set on tplPath in concurrency http request?

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

1条回答 默认 最新

  • 已采纳
    douba1067 douba1067 2018-06-15 09:53

    Using package level variables is not always good or always bad. Depending on problem.

    The only thing about this specific code example, is that you could possibly end up in a state where you are locking and unlocking in multiple places in code.

    If you choose to go down this route; which is fine, consider extracting the tplPath and mutex into a type.

    // create type and expose values through getters and setters 
    // to ensure the mutex logic is encapsulated.
    type path struct {
        mu sync.Mutex
        val string
    func (p *path) setPath(path string) {
        defer p.mu.Unlock()
        p.val = path
    func (p *path) path() string {
        defer p.mu.Unlock()
        return p.val
    var tplPath *path
    func init() {
        // use package init to make sure path is always instantiated
        tplPath = new(path)
    func Prepare(c *gin.Context) {
    点赞 评论 复制链接分享