对于map线程不安全的并发读写的问题最好不使用sync.map,系统库还存在问题

系统提供了sync.map最好不要用,系统自带线程安全的map还存在bug那么

选择map+线程锁或读写锁看情况

 

sync.map的bug。。

 

tmp:=sync.Map{}
tmp.Store("a","b")
tmp.Store("b","c")
tmp.Store("c","c")
fmt.Println(tmp)
msg,_:= json.Marshal(tmp)
fmt.Println(len(msg))
fmt.Println(msg)

 

-----------------------------------

{{0 0} {{map[] true}} map[c:0xc000006038 a:0xc000006028 b:0xc000006030] 0}
2
[123 125]

package main

import (
	"encoding/json"
	"fmt"
	"sync"
)

func main() {
	tmp := sync.Map{}
	pp := make(map[string]string)
	tmp.Store("a", "b")
	tmp.Store("b", "c")
	tmp.Store("c", "c")
	fmt.Printf("%+v\n", tmp)
	msg, _ := json.Marshal(tmp)
	fmt.Println(len(msg))
	fmt.Println(msg)



	tmp.Range(func(k, v interface{}) bool {
		ss, ok1 := k.(string)
		vv, ok2 := v.(string)
		if ok1 && ok2 {
			pp[ss] = vv
		}
		return true
	})




	fmt.Println("----0", pp)
	bb, err := json.Marshal(pp)
	if err==nil {
		fmt.Println(string(bb))
	}
}

{mu:{state:0 sema:0} read:{v:{m:map[] amended:true}} dirty:map[c:0xc00007a028 a:0xc00007a018 b:0xc00007a020] misses:0}
2
[123 125]
----0 map[a:b b:c c:c]
{"a":"b","b":"c","c":"c"}

如此相当于json.Marshal()只支持标准map,对于sync.Map要再次处理才可以

 

你可能感兴趣的:(go,物联网)