当前位置:网站首页>Concurrent writing of maps in golang

Concurrent writing of maps in golang

2022-06-24 14:33:00 KunkkaWu

principle

golang Medium map Not thread safe , Therefore, it cannot be used directly in the case of concurrency map.

Negative example

import (

    "strconv"

    "time"

)



var m = make(map[string]interface{})



func main() {

    testMap(m)

    time.Sleep(2 * time.Second)

}



func testMap() {

    go func() {

        for i := 0; i < 10; i++ {

            name := "WangWu" + strconv.Itoa(i)

            writeMap(m, name, i)

        }

    }()

    go func() {

        for i := 0; i < 10; i++ {

            name := "ZhuoQi" + strconv.Itoa(i)

            writeMap(m, name, i)

        }

    }()

}



func writeMap(m map[string]int, key string, val int) {

    m[key] = val

}

Runtime , Will report a mistake :

fatal error: concurrent map writes

terms of settlement

1. Map Lock

package main



import (

    "fmt"

    "strconv"

    "sync"

    "time"

)

//  Definite lock 

var locker = &sync.RWMutex{}

var m = make(map[string]interface{})



func main() {

    testMap()

    time.Sleep(2 * time.Second)

    fmt.Println(m)

}



func testMap() {

    go func() {

        for i := 0; i < 10; i++ {

            name := "WangWu" + strconv.Itoa(i)

            writeMap(name, i)

        }

    }()

    go func() {

        for i := 0; i < 10; i++ {

            name := "ZhuoQi" + strconv.Itoa(i)

            writeMap(name, i)

        }

    }()

}



func writeMap(key string, val int) {

    locker.Lock()

    m[key] = val

    locker.Unlock()

}
  1. Use sync.Map
package main



import (

    "fmt"

    "strconv"

    "sync"

    "time"

)



var m = sync.Map{}



func main() {

    testMap()

    time.Sleep(2 * time.Second)

    m.Range(func(k, v interface{}) bool {

        fmt.Println("map:", k, v)

        return true

    })

}



func testMap() {

    go func() {

        for i := 0; i < 10; i++ {

            name := "WangWu" + strconv.Itoa(i)

            m.Store(name, i)

        }

    }()

    go func() {

        for i := 0; i < 10; i++ {

            name := "ZhuoQi" + strconv.Itoa(i)

            m.Store(name, i)

        }

    }()

}
原网站

版权声明
本文为[KunkkaWu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241426126607.html