1.读写都加锁
package main
import (
"fmt"
"sync"
"time"
)
var slice = make([]int64, 0)
func main() {
var l sync.Mutex
go func() {
for {
time.Sleep(time.Second)
l.Lock()
slice = append(slice, time.Now().Unix())
l.Unlock()
}
}()
for m := 0; m < 5; m++ {
go func() {
for {
l.Lock()
time.Sleep(time.Millisecond * 100)
fmt.Println(len(slice))
l.Unlock()
}
}()
}
time.Sleep(time.Hour)
}
2.读加锁,写不加锁
package main
import (
"fmt"
"sync"
"time"
)
var slice = make([]int64, 0)
func main() {
var l sync.RWMutex //读写锁
go func() {
for {
time.Sleep(time.Second)
l.Lock()
slice = append(slice, time.Now().Unix())
l.Unlock()
}
}()
for m := 0; m < 5; m++ {
go func() {
for {
l.RLock()
time.Sleep(time.Millisecond * 100)
fmt.Println(len(slice))
l.RUnlock()
}
}()
}
time.Sleep(time.Hour)
}
3.原子加锁
package main
import (
"fmt"
"sync/atomic"
"time"
"unsafe"
)
var slice = &[]int{}
var slicePtr = unsafe.Pointer(slice)
func main() {
go func() {
for {
time.Sleep(time.Second)
slicePtr = atomic.LoadPointer(&slicePtr)
slice1 := (*[]int64)(slicePtr)
slice2 := append(*slice1, time.Now().UnixNano())
atomic.StorePointer(&slicePtr, unsafe.Pointer(&slice2))
}
}()
for m := 0; m < 5; m++ {
go func() {
for {
time.Sleep(time.Millisecond * 100)
ptr := atomic.LoadPointer(&slicePtr)
slice := (*[]int64)(ptr)
fmt.Println(len(*slice))
}
}()
}
time.Sleep(time.Hour)
}