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...