Skip to content

Instantly share code, notes, and snippets.

@Leo-stone-dot
Created August 17, 2022 06:38
Show Gist options
  • Save Leo-stone-dot/b5ff7264008a1e115b7d11cd702f21b0 to your computer and use it in GitHub Desktop.
Save Leo-stone-dot/b5ff7264008a1e115b7d11cd702f21b0 to your computer and use it in GitHub Desktop.
map 的并发读写
package tests
import (
"sync"
"testing"
)
func TestMap(t *testing.T) {
ids := []int64{1, 2, 3, 1, 2, 3}
parallelIndexMap(ids)
parallelMap(ids)
}
func parallelIndexMap(ids []int64) {
type info struct {
id int64
}
var maps = make(map[int64]int, len(ids))
var array = make([]*info, len(ids))
for i, id := range ids {
maps[id] = i
}
var wg = &sync.WaitGroup{}
for _, id := range ids {
wg.Add(1)
go func(id int64) {
defer wg.Done()
index := maps[id]
array[index] = &info{id: id}
}(id)
}
wg.Wait()
}
func parallelMap(ids []int64) {
type info struct {
id int64
}
var maps = make(map[int64]*info, len(ids))
var wg = &sync.WaitGroup{}
for _, id := range ids {
wg.Add(1)
go func(id int64) {
defer wg.Done()
maps[id] = &info{
id: id,
}
}(id)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment