use
- Store in
- Load reads, and it returns two values, the first one is value, and the second one is a bool variable indicating whether or not key exists
- Delete Delete
- LoadOrStore Read if it exists. Write if it does not exist
- Range iterates over all keys and passes the iterated key and value into the callback function for function call. If the callback function returns false, the iterating ends. Otherwise, all keys are iterated.
package main
import (
"fmt"
"golang.org/x/net/websocket"
"sync"
)
// All even numbers are deleted during the traverse. The result: all even numbers are deleted
func fun1(a) {
x := sync.Map{}
/ / build
for i := 0; i < 100; i++ {
x.Store(i, i)
}
// Delete even numbers
x.Range(func(k, v interface{}) bool {
if k.(int) %2= =0 {
x.Delete(k)
}
return true
})
// Iterate over the rest of the print
cout := 0
x.Range(func(k, v interface{}) bool {
fmt.Println(k, v)
cout++
return true
})
// You will find 50, indicating that all even numbers have been deleted
fmt.Println("The number of remaining elements after deleting an even number,cout:", cout)
}
// All elements are deleted during the traverse. The result: all elements are deleted
func fun2(a) {
x := sync.Map{}
/ / build
for i := 0; i < 100; i++ {
x.Store(i, i)
}
// Delete even numbers
x.Range(func(k, v interface{}) bool {
x.Delete(k)
return true
})
// Iterate over the rest of the print
cout := 0
x.Range(func(k, v interface{}) bool {
fmt.Println(k, v)
cout++
return true
})
// Will find 0, indicating that all elements have been deleted
fmt.Println("Number of remaining elements after all deletion,cout:", cout)
}
type Game struct {
m_UserList sync.Map
}
func main(a) {
// Delete half of the time
fun1()
// Delete all elements during the iterate
fun2()
}
// Look up ws by userId
func (r *Game) FindSocketByUserID(userId int) *websocket.Conn {
var ws *websocket.Conn
r.m_UserList.Range(func(k, v interface{}) bool {
switch v.(type) {
case *websocket.Conn:
userId_k := k.(int)
if userId == userId_k {
ws = v.(*websocket.Conn)
return false// Return false to stop traversal}}return true // Return true to continue traversal
})
return ws
}
// Add the user list
func (r *Game) AddUserList(userId int, ws *websocket.Conn) {
if vv, ok := r.m_UserList.LoadOrStore(userId, ws); ok {
fmt.Println("Add game user list:", vv)
}
}
// Delete the user list
func (r *Game) DelUserList(userId int) {
r.m_UserList.Delete(userId)
}
Copy the code
The principle of analysis
//todo