-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyncmap.go
54 lines (46 loc) · 1009 Bytes
/
syncmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"fmt"
"sync"
)
func main() {
var sm sync.Map
// store values
sm.Store("name", "Akkshay")
sm.Store("age", 20)
sm.Store("language", "Go")
// load & print
if name, ok := sm.Load("name"); ok {
fmt.Printf("Name: %s\n", name)
}
if age, ok := sm.Load("age"); ok {
fmt.Printf("Age: %d\n", age)
}
if language, ok := sm.Load("language"); ok {
fmt.Printf("Language: %s\n", language)
}
// delete a value from the sync.Map
sm.Delete("age")
// range sync.Map
fmt.Println("Contents of sync.Map:")
sm.Range(func(key, value interface{}) bool {
fmt.Printf("%s: %v\n", key, value)
return true
})
// concurrent access to sync.Map
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
sm.Store(fmt.Sprintf("key%d", i), i)
}(i)
}
wg.Wait()
// final contents of sync.Map
fmt.Println("Final contents of sync.Map:")
sm.Range(func(key, value interface{}) bool {
fmt.Printf("%s: %v\n", key, value)
return true
})
}