在Go语言中,为了保证并发编程的一致性,我们可以采用以下方法:
sync
包提供了Mutex
结构体,可以用来实现互斥锁。使用Lock()
方法加锁,Unlock()
方法解锁。package main
import (
"fmt"
"sync"
)
var counter int
var lock sync.Mutex
func increment() {
lock.Lock()
counter++
lock.Unlock()
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
sync
包提供了RWMutex
结构体,可以用来实现读写锁。使用RLock()
方法加读锁,RUnlock()
方法解读锁,Lock()
方法加写锁,Unlock()
方法解写锁。package main
import (
"fmt"
"sync"
)
var data map[string]string
var rwLock sync.RWMutex
func readData(key string) {
rwLock.RLock()
value := data[key]
rwLock.RUnlock()
fmt.Println("Read:", value)
}
func writeData(key, value string) {
rwLock.Lock()
data[key] = value
rwLock.Unlock()
}
func main() {
data = make(map[string]string)
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key := fmt.Sprintf("key%d", i)
value := fmt.Sprintf("value%d", i)
writeData(key, value)
}(i)
}
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key := fmt.Sprintf("key%d", i%10)
readData(key)
}(i)
}
wg.Wait()
}
sync/atomic
包提供了一组原子操作函数,如AddInt32()
、CompareAndSwapInt32()
等。package main
import (
"fmt"
"sync"
"sync/atomic"
)
var counter int32
var wg sync.WaitGroup
func increment() {
atomic.AddInt32(&counter, 1)
}
func main() {
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, ch chan int) {
defer wg.Done()
for i := range ch {
fmt.Println("Received:", i)
}
}
func main() {
ch := make(chan int, 100)
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go worker(&wg, ch)
}
for i := 0; i < 100; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
这些方法可以单独使用,也可以组合使用,以满足不同的并发编程需求。在实际编程中,需要根据具体场景选择合适的同步策略。