go 线程同步
代碼來源于《Go語言開發(fā)教程》
// 線程同步: sync.Mutexpackage mainimport ("errors""fmt""sync" )type MyMap struct {mp map[string]intmutex *sync.Mutex }func (this *MyMap) Get(key string) (int, error) {this.mutex.Lock()i, ok := this.mp[key]this.mutex.Unlock()if !ok {return i, errors.New("not exist")}return i, nil }func (this *MyMap) Set(key string, v int) {this.mutex.Lock()defer this.mutex.Unlock()this.mp[key] = v }func SetValue(m *MyMap) {var a runea = 'a'for i := 0; i < 10; i++ {m.Set(string(a+rune(i)), i)} }func (this *MyMap) Display() {this.mutex.Lock()defer this.mutex.Unlock()for k, v := range this.mp {fmt.Println(k, "=", v)} }func main() {m := &MyMap{mp: make(map[string]int), mutex: new(sync.Mutex)}go SetValue(m)go m.Display()var str stringfmt.Scan(&str) }創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結
- 上一篇: 电脑开机后,就会自动运行chkdsk,我
- 下一篇: pycharm 快捷键介绍