关于配置读写的一种线程安全实现
type Config struct {
Value string
Expire int64
rwLock sync.RWMutex
}
func (config *Config) GetValue() (string, bool) {
val := ""
ok := false
config.rwLock.RLock()
if time.Now().Unix()-config.Expire < 5 {
ok = true
val = config.Value
}
config.rwLock.RUnlock()
return val, ok
}
func (config *Config) UpdateValue(name string) (string, bool) {
val := ""
ok := false
config.rwLock.Lock()
if time.Now().Unix()-config.Expire >= 5 {
config.Expire = time.Now().Unix()
config.Value = fmt.Sprintf("val:%+v", config.Expire)
val = config.Value
ok = true
time.Sleep(1 * time.Second)
//fmt.Printf("update_by:%+v,new:%+v\n", name, val)
}
config.rwLock.Unlock()
return val, ok
}
func GetOrUpdate(c *Config, name string) string {
val, ok := c.GetValue()
//fmt.Printf("read name:%+v,now:%+v\n", name, now)
if !ok {
fmt.Printf("pre_update:time:%+v,name:%+v\n", time.Now().Unix(), name)
new, updateOk := c.UpdateValue(name)
fmt.Printf("update:time:%+v,name:%+v,ok:%+v,new:%+v\n", time.Now().Unix(), name, updateOk, new)
return new
}
return val
}
func main() {
c := Config{}
for i := 0; i < 3; i++ {
go func(name string) {
for loop := true; loop; {
GetOrUpdate(&c, name) // 如果传c就会有问题
}
}(fmt.Sprintf("%v", i))
}
time.Sleep(100 * time.Second)
}
两个字符串的比较,忽略字符顺序
func compareElementFromStr(str1 string, str2 string) bool {
if len(str1) != len(str2) {
return false
}
getRuneListByOrder := func(str string) []rune {
var list []rune
for _, te := range str {
list = append(list, te)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
list1 := getRuneListByOrder(str1)
list2 := getRuneListByOrder(str2)
for i := 0; i < len(list1); i++ {
if list2[i] != list2[i] {
return false
}
}
return true
}