1 回答

TA貢獻1864條經(jīng)驗 獲得超6個贊
var globalvar []string
func main() {
var mu sync.Mutex
go func() {
for {
// Block access to a global variable, so that
// no one can change it outside the goroutine.
// If it's already locked outside the goroutine,
// then wait for unlocking.
mu.Lock()
// Some actions with a global variable...
fmt.Printf("%v\n", globalvar)
// Unlocking access to a global variable
mu.Unlock()
// Some code...
}
}()
for i := 0; i < 255; i++ {
// Block access to a global variable.
// If it's already locked inside the goroutine,
// then wait for unlocking.
mu.Lock()
// Some actions with a global variable
globalvar = append(globalvar, "Str #"+strconv.Itoa(i))
// Unlock access
mu.Unlock()
// Some code...
}
}
您還可以定義一個特殊的結(jié)構(gòu),其中包含互斥體、值和更改其值的方法。是這樣的:
type TpusContainer struct {
mu sync.Mutex
value []string
}
func (t *TpusContainer) RemoveIndex(i int) {
t.mu.Lock()
defer t.mu.Unlock()
t.value = RemoveIndex(t.value, i)
}
func (t *TpusContainer) Append(elem string) {
t.mu.Lock()
defer t.mu.Unlock()
t.value = append(t.value, elem)
}
func (t *TpusContainer) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return fmt.Sprintf("%v", t.value)
}
var Tpus TpusContainer
func main() {
go func() {
for {
fmt.Printf("%v\n", Tpus)
}
}()
for i := 0; i < 255; i++ {
Tpus.RemoveIndex(0)
Tpus.Append("Some string #"+strconv.Itoa(i))
}
}
就個人而言,我更喜歡第二種方法。
- 1 回答
- 0 關注
- 132 瀏覽
添加回答
舉報