dpk20361 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) {
    mutex.Lock()
    tplPath = "abc"
    mutex.Unlock()
}

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 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) {
        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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c