duanou1904 2017-11-05 21:00
浏览 163
已采纳

Go包中的全局变量

I'm interested in using a Go package that uses a global variable which, for my application, is a key "variable". Each time I call this package, I want to set that variable (it's exported). And I'm calling it from various Go routines. Is there a recommended strategy for sequencing/syncing my calls to that package so that my code isn't colliding on that global variable?

Here's an example:

package main

import (
    "fmt"
    "sync"
    "time"

    "github.com/jameshaskell/_sketches/globalvars/testlib"
)

var wg sync.WaitGroup

func gr(i int) {
    defer wg.Done()
    testlib.GlobalVar = i
    duration := time.Duration(i) * time.Millisecond
    time.Sleep(duration)
    fmt.Printf("   pause %d DONE
", i)
    fmt.Printf("      global var: %d should be: %d  TestFunc: %s
", testlib.GlobalVar, i, testlib.TestFunc())
}

func main() {
    for i := 0; i <= 10; i += 1 {
        wg.Add(1)
        go gr(i)
    }
    wg.Wait()
}

The package I'm trying to access would be like:

package testlib

import "fmt"

var GlobalVar int

func TestFunc() string {
    return fmt.Sprintf("GlobalVar: %d
", GlobalVar)
}

NOTE: the package I'm hoping to use (having the global var) isn't mine...

  • 写回答

3条回答 默认 最新

  • douzhongjian0752 2017-11-06 00:38
    关注

    Is this variable intended to be used this way? May be there’re some specific setters/getters for it? Does documentation have some info about?

    I think code becomes very fragile because you do not control all accesses to the variable. You may serialize access from your code with a mutex. But another lib’s code doesn’t know about your it. Moreover it can change suddenly in new versions or bug fixes.

    So I prefer:

    1. To read about it in official docs

    2. If documentation allows, and I can’t avoid to use it, protect access to the variable with sync/mutex/atomic/channel depending on a task.

    3. Prepare tests to cover different cases with the variable

    4. Run race condition detector as part of my CI tests.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码