The principle and use of sync.map in golang

Retrieved from: https://blog.csdn.net/xiaohenghengmua/article/details/111693723

For personal backup only, please see the original text for browsing

 

1. Why is map thread unsafe?

When zipper, thread is not safe

2. Overview of the principle of sync.map

The implementation of sync.map is to rely on two maps to separate the read operation and the write operation, and then merge the dirty map into the read map as needed. Compared with the implementation of optimistic locking, when the writing process is executing, the reading process may also be performed on the read map. detailed:

a. The two fields of read and dirty will be read and written separately, the read data is stored in the read-only field read, and the newly written data is stored in the dirty field

b. When reading, it will query read first, and then query dirty if it does not exist, and only write dirty when writing

c. Reading does not need to be locked, while reading or writing dirty requires locking

d. There is also a misses field to count the number of times the read has been penetrated (being penetrated refers to the situation where the dirty needs to be read), if more than a certain number of times, the dirty data will be synchronized to the read

e. For deleted data, directly mark to delay deletion

3. Use

	var ma sync.Map// 该类型是开箱即用,只需要声明既可
    ma.Store("key", "value") // 存储值
    ma.Delete("key") //删除值
    ma.LoadOrStore("key", "value")// 获取值,如果没有则存储
    fmt.Println(ma.Load("key"))//获取值
    
    //遍历
    ma.Range(func(key, value interface{}) bool {
        fmt.Printf("key:%s ,value:%s \n", key, value)
        //如果返回:false,则退出循环,
        return true
    })

 

Guess you like

Origin blog.csdn.net/chushoufengli/article/details/114628932