在Go語言中,為了保證并發(fā)編程的安全性,我們可以采用以下幾種方法:
sync.Mutex
或sync.RWMutex
來實(shí)現(xiàn)互斥鎖。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
來實(shí)現(xiàn)讀寫鎖。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
包提供了原子操作的實(shí)現(xiàn)。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語言中實(shí)現(xiàn)并發(fā)編程的安全性。在實(shí)際開發(fā)中,你需要根據(jù)具體場(chǎng)景選擇合適的同步原語。