在Go语言中,实现并发安全主要依赖于以下几种方式:
sync.Mutex
结构体来实现互斥锁。import "sync"
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
sync.RWMutex
结构体来实现读写锁。import "sync"
var rwMu sync.RWMutex
var sharedData map[string]string
func readData(key string) string {
rwMu.RLock()
defer rwMu.RUnlock()
return sharedData[key]
}
func writeData(key, value string) {
rwMu.Lock()
defer rwMu.Unlock()
sharedData[key] = value
}
sync/atomic
包来实现原子操作。import "sync/atomic"
var counter int32
func increment() {
atomic.AddInt32(&counter, 1)
}
func getCounter() int32 {
return atomic.LoadInt32(&counter)
}
sync.Map
是一个线程安全的map实现,它是基于不可变数据结构的。import "sync"
var sharedMap sync.Map
func storeData(key, value interface{}) {
sharedMap.Store(key, value)
}
func getData(key interface{}) interface{} {
return sharedMap.Load(key)
}
import "fmt"
func producer(ch chan<- int) {
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
}
func consumer(ch <-chan int, done chan<- bool) {
for num := range ch {
fmt.Println("Received:", num)
}
done <- true
}
func main() {
ch := make(chan int)
done := make(chan bool)
go producer(ch)
go consumer(ch, done)
<-done
}
通过以上方法,Go语言提供了丰富的并发安全机制,可以根据具体场景选择合适的方法来实现并发安全。