在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访问共享资源。你可以使用互斥锁、读写锁、通道或原子操作来实现这一目标。在实际编程中,你需要根据具体场景选择合适的同步机制。