在Go語言中,競態條件(race condition)是指多個并發執行的goroutine訪問共享資源時,由于操作順序不當導致的不確定結果。為了避免競態條件,你可以采用以下方法:
sync.Mutex
結構體來實現互斥鎖。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)
}
import (
"fmt"
"sync"
)
var (
data = []int{0}
rwMutex sync.RWMutex
)
func read() int {
rwMutex.RLock()
defer rwMutex.RUnlock()
return data[0]
}
func write(value int) {
rwMutex.Lock()
defer rwMutex.Unlock()
data[0] = value
}
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
read()
}()
}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(value int) {
defer wg.Done()
write(value)
}(i)
}
wg.Wait()
fmt.Println("Data:", data[0])
}
import (
"fmt"
"sync"
)
func increment(counter chan int, wg *sync.WaitGroup) {
defer wg.Done()
counter <- 1
}
func main() {
var counter int
var wg sync.WaitGroup
counterChan := make(chan int, 1)
wg.Add(10)
for i := 0; i < 10; i++ {
go increment(counterChan, &wg)
}
go func() {
wg.Wait()
close(counterChan)
}()
for value := range counterChan {
counter += value
}
fmt.Println("Counter:", counter)
}
sync/atomic
包提供了一些原子操作函數,如AddInt32
、CompareAndSwapInt32
等。import (
"fmt"
"sync/atomic"
)
var counter int32
func increment() {
atomic.AddInt32(&counter, 1)
}
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)
}
總之,要避免競態條件,你需要確保在同一時間只有一個goroutine訪問共享資源。你可以使用互斥鎖、讀寫鎖、通道或原子操作來實現這一目標。在實際編程中,你需要根據具體場景選擇合適的同步機制。