@go学习错误记录
互斥学习
问题场景:多线程与全局变量
当多个线程同时调用一个函数,若该函中使用了全局变量,则应当小心,可能造成数据的被覆盖。
- 测试代码:
package main
import (
"fmt"
"strconv"
"time"
)
type voice struct {
}
var strVoice string
func printfVoice(str string) {
strVoice = str
time.Sleep(1 * time.Microsecond)
fmt.Println(strVoice)
}
func (v *voice) say(s string) {
str := s
printfVoice(str)
}
func main() {
v := voice{}
go func() {
for i := 0; i < 10; i++ {
v.say("hello" + strconv.Itoa(i))
}
}()
go func() {
for i := 0; i < 10; i++ {
v.say("world" + strconv.Itoa(i))
}
}()
fmt.Println("等待程序运行结束")
time.Sleep(1000 * time.Millisecond)
fmt.Println("程序运行结束")
}
测试结果
2. 解决方法
加入互斥锁
var lock sync.Mutex = sync.Mutex{}
func printfVoice(str string) {
lock.Lock()
defer lock.Unlock()
strVoice = str
time.Sleep(1 * time.Microsecond)
fmt.Println(strVoice)
}
测试结果:
go学习新手。若有问题,还请各位赐教!!!