数据竞争是多个 goroutine 并发访问共享数据而无同步保护,解决方案包括使用互斥锁和读写锁。资源争用是多个 goroutine 争抢稀缺资源,可通过资源限额、并发队列和死锁检测解决。实战案例提供了线程安全计数器和使用并发队列共享资源的示例。

简介
在并发编程中,数据竞争和资源争用是常见的错误来源,如果不妥善解决,会引发难以调试的问题。本文将探讨如何在 Go 语言中识别和解决这些问题,并提供实战案例以加深理解。
数据竞争
立即学习“go语言免费学习笔记(深入)”;
数据竞争是指多个 goroutine 并发访问共享数据而没有同步保护,导致数据不一致。例如:
var counter int
func incrementCounter() {
counter++
}
func decrementCounter() {
counter--
}
func main() {
waitGroup := new(sync.WaitGroup)
waitGroup.Add(2)
go func() {
for i := 0; i < 100; i++ {
incrementCounter()
}
waitGroup.Done()
}()
go func() {
for i := 0; i < 100; i++ {
decrementCounter()
}
waitGroup.Done()
}()
waitGroup.Wait()
fmt.Println(counter) // 输出可以是任意值
}在这个例子中,counter 变量在多个 goroutine 之间共享,但在没有同步的情况下被并发访问,可能会导致数据竞争。
解决方法:
sync.Mutex):互斥锁允许一次只允许一个 goroutine 访问共享数据,从而防止数据竞争。sync.RWMutex):读写锁将锁分为读锁和写锁,允许多个 goroutine并发读取共享数据,同时只能由一个 goroutine写入数据。资源争用
资源争用是指多个 goroutine 竞争同一有限资源,例如 CPU 时间或内存,导致性能下降。例如:
var channel = make(chan int, 1)
func sendChannelData() {
for {
channel <- 1
}
}
func receiveChannelData() {
for {
<-channel
}
}
func main() {
go sendChannelData()
go receiveChannelData()
}在这个例子中,两个 goroutine 竞争写入和读取同一通道 channel。这会导致 goroutine 交替执行,性能明显下降。
解决方法:
sync.Pool 或 channels,以确保公平的访问。runtime.GOMAXPROCS 函数和 runtime.NumGoroutine 函数来检测和避免死锁。实战案例
一个共享资源的线程安全的计数器
import (
"sync/atomic"
)
type ThreadsafeCounter struct {
value int64
}
func (c *ThreadsafeCounter) Increment() {
atomic.AddInt64(&c.value, 1)
}
func (c *ThreadsafeCounter) Decrement() {
atomic.AddInt64(&c.value, -1)
}
func (c *ThreadsafeCounter) Value() int64 {
return atomic.LoadInt64(&c.value)
}一个使用并发队列的共享资源
import (
"sync"
"container/list"
)
type ConcurrentQueue struct {
items *list.List
lock sync.Mutex
}
func NewConcurrentQueue() *ConcurrentQueue {
return &ConcurrentQueue{
items: list.New(),
}
}
func (q *ConcurrentQueue) Push(item interface{}) {
q.lock.Lock()
defer q.lock.Unlock()
q.items.PushBack(item)
}
func (q *ConcurrentQueue) Pop() (item interface{}, ok bool) {
q.lock.Lock()
defer q.lock.Unlock()
if q.items.Len() > 0 {
item = q.items.Remove(q.items.Front())
return item, true
}
return nil, false
}
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号