在Go语言中,为了保证并发编程的安全性,我们可以采用以下几种方法:
sync.Mutex
或sync.RWMutex
来实现互斥锁。import (
"fmt"
"sync"
)
var (
counter = 0
mutex sync.Mutex
)
func increment() {
mutex.Lock()
counter++
mutex.Unlock()
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
sync.RWMutex
来实现读写锁。import (
"fmt"
"sync"
)
var (
data = []int{1, 2, 3, 4, 5}
rwMutex sync.RWMutex
)
func readData() {
rwMutex.RLock()
defer rwMutex.RUnlock()
fmt.Println("Read:", data)
}
func writeData(value int) {
rwMutex.Lock()
defer rwMutex.Unlock()
data = append(data, value)
fmt.Println("Write:", value)
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
readData()
}()
}
for i := 0; i < 3; i++ {
wg.Add(1)
go func(value int) {
defer wg.Done()
writeData(value)
}(i)
}
wg.Wait()
}
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup, ch chan int) {
defer wg.Done()
for value := range ch {
fmt.Printf("Worker %d received value: %d\n", id, value)
}
}
func main() {
var wg sync.WaitGroup
ch := make(chan int)
for i := 0; i < 5; i++ {
wg.Add(1)
go worker(i, &wg, ch)
}
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
sync/atomic
包提供了原子操作的实现。package main
import (
"fmt"
"sync"
"sync/atomic"
)
var counter int64
func increment() {
atomic.AddInt64(&counter, 1)
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
通过使用这些方法,你可以在Go语言中实现并发编程的安全性。在实际开发中,你需要根据具体场景选择合适的同步原语。