【问题标题】:Declare mutex variable in package level is good practice? [closed]在包级别声明互斥变量是好习惯吗? [关闭]
【发布时间】:2018-11-25 03:25:46
【问题描述】:

在一个包中,我声明了一些变量和一个互斥变量。 我想用它来锁定或解锁包级别变量的 get/set。

var mutex sync.Mutex
var tplPath = ""

func Prepare(c *gin.Context) {
    mutex.Lock()
    tplPath = "abc"
    mutex.Unlock()
}

在并发 http 请求中使用互斥锁可以防止 tplPath 上的 get/set 竞争条件是否可以被视为一种好习惯?

【问题讨论】:

  • 这种用法看起来不错,但您不应该使用单个互斥锁来保护所有全局变量,因为您可能会不必要地阻塞 goroutines 尝试仅访问其他变量。另见相关:When do you embed mutex in struct in Go?
  • 好的做法很模糊。

标签: http go concurrency global-variables mutex


【解决方案1】:

使用包级变量并不总是好的或坏的。视问题而定。

关于这个特定代码示例的唯一问题是,您最终可能会处于在代码中的多个位置锁定和解锁的状态。

如果你选择走这条路;这很好,考虑将tplPathmutex 提取到一个类型中。

// 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) {
    p.mu.Lock()
    defer p.mu.Unlock()
    p.val = path
}

func (p *path) path() string {
    p.mu.Lock()
    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) {
    tplPath.setPath("abc")
}

【讨论】:

    猜你喜欢
    • 2018-04-07
    • 2020-11-06
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2020-08-25
    • 2021-03-15
    • 2021-10-30
    • 2013-03-30
    相关资源
    最近更新 更多