hhstore / blog

My Tech Blog: about Mojo / Rust / Golang / Python / Kotlin / Flutter / VueJS / Blockchain etc.
https://github.com/hhstore/blog/issues
296 stars 24 forks source link

Golang: Common Knowledge #141

Open hhstore opened 5 years ago

hhstore commented 5 years ago

go 的踩坑系列:

map:


package main

import "fmt"

func main() {
    //ch := make(chan int)

    Map := make(map[int]int)
    Map[100] = 1000
    Map[120] = 1200
    //go initMap(Map, 10, ch)
    //<-ch // 完成初始化

    // 并发写, 一定异常:
    panicWrite(Map, 100)

    // 只读, 没问题, 有写, 必有问题
    safeRead(Map, 100000)

    // 并发读和写一起, 一定异常:
    panicWriteAndRead(Map, 100)

    fmt.Println("map:", Map)

}

func initMap(m map[int]int, num int, ch chan int) {
    for i := 0; i < num; i++ {
        m[i] = i + 100
    }
    ch <- 0 // 完成初始化
}

func panicWrite(Map map[int]int, num int) {
    for i := 0; i < num; i++ {
        go writeMap(Map, i, i)
    }
}

func safeRead(Map map[int]int, num int) {

    fmt.Println("map:", Map)
    for i := 0; i < num; i++ {
        go readMap(Map, i)
    }
}
func panicWriteAndRead(Map map[int]int, num int) {
    for i := 0; i < num; i++ {
        go writeMap(Map, i, i)
        go readMap(Map, i)
    }
}

func readMap(Map map[int]int, key int) int {
    fmt.Println("read", Map[key])
    return Map[key]
}

func writeMap(Map map[int]int, key int, value int) {
    Map[key] = value
}

sync.Map: