Atomic

无锁编程--atomic.Value

published on
背景 多个goroutine都会读写同一个对象时,必然会有竞争。读写锁或者互斥锁就是解决这种问题的终极方法,但同时性能也是最差的,go在atomic库提供了Value这个类型,实现无锁操作。 实现 type HomeCache map[string]int var homePageInfo atomic.Value func updateHomeCache() error { data := HomeCache{} queryStr := "SELECT source,type,value,wihome FROM wihome_index" rows, _ := adb.DB.Query(queryStr) var source, typ, wihome int var value, key string for rows.Next() { rows.Scan(&source, &typ, &value, &wihome) key = fmt.Sprintf("%d__%d__%s", source, typ, value) data[key] = wihome } if rows.Err() != nil { return rows.Err() } homePageInfo.Store(data) return nil } func GetHomeIdx(source int, did string, mid int, node string) (idx int) { data := homePageInfo. Read More...