侧边栏壁纸
  • 累计撰写 71 篇文章
  • 累计创建 87 个标签
  • 累计收到 5 条评论

目 录CONTENT

文章目录

golang中Map的并发写入

KunkkaWu
2022-06-14 / 0 评论 / 4 点赞 / 13,481 阅读 / 315 字 / 正在检测是否收录...

原理

golang中的map不是线程安全的,所以在并发的情况下不能直接使用map。

反面例子

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
}


运行时,会报错:

fatal error: concurrent map writes

解决办法

1. Map加锁

package main

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)
// 定义锁
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. 使用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)
		}
	}()
}

4

评论区