面试题答案
一键面试- 检测工具:Go语言提供了
go tool race
工具来检测数据竞争问题。 - 并发代码示例:
package main
import (
"fmt"
"sync"
)
var counter int
func increment(wg *sync.WaitGroup) {
defer wg.Done()
counter++
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go increment(&wg)
}
wg.Wait()
fmt.Println("Final counter value:", counter)
}
- 使用工具检测: 在命令行中进入包含上述代码的目录,执行以下命令:
go build -race
./<可执行文件名>
如果存在数据竞争,go tool race
会输出详细的信息,指出竞争发生的位置等。在上述示例中,counter++
这一行会引发数据竞争,因为多个goroutine同时访问和修改counter
。通过go tool race
可以检测到这个问题。