0

并发小白 sync.Mutex 疑问,求大佬指点

 2 years ago
source link: https://studygolang.com/articles/35833
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

并发小白 sync.Mutex 疑问,求大佬指点

gmmstrive · 7天之前 · 1236 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

疑问

为什么 main 方法中循环打印 myMap 时还要加锁?不加锁 go build -race cmd/main.go 编译运行时会提示有两个数据存在竞争关系

package main

import (
    "fmt"
    "sync"
    "time"
)

var (
    myMap = make(map[int]int, 10)
    lock  sync.Mutex
)

func test(n int) {

    res := 1
    for i := 1; i <= n; i++ {
        res *= i
    }

    lock.Lock()
    defer lock.Unlock()
    myMap[n] = res

}

func main() {

    for i := 1; i <= 20; i++ {
        go test(i)
    }

    time.Sleep(time.Second * 10)

    //lock.Lock()
    for i, v := range myMap {
        fmt.Printf("map[%d] = %d \n \n", i, v)
    }
    //lock.Unlock()

}

有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK