Created
August 17, 2022 06:38
-
-
Save Leo-stone-dot/b5ff7264008a1e115b7d11cd702f21b0 to your computer and use it in GitHub Desktop.
map 的并发读写
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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