goland读写锁 - Go语言中文社区

goland读写锁


 关于配置读写的一种线程安全实现

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)
}

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_37325947/article/details/124569145
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2022-12-29 20:46:38
  • 阅读 ( 315 )
  • 分类:Goland

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢