争用条件是由于对共享资源的不同步访问而引起的,并试图同时读取和写入该资源。
原子函数提供了用于同步访问整数和指针的低级锁定机制。原子功能通常用于修复竞争条件。
中的功能 原子 下 同步 软件包通过锁定对共享资源的访问来提供支持同步goroutine的支持。
package main
import (
"fmt"
"runtime"
"同步"
"同步/atomic"
)
var (
counter int32 // counter is a variable incremented by all goroutines.
wg 同步.WaitGroup // wg is used to wait for the program to finish.
)
func main() {
wg.Add(3) // Add a count of two, one for each goroutine.
go increment("Python")
go increment("Java")
go increment("高朗")
wg.Wait() // Wait for the goroutines to finish.
fmt.Println("Counter:", counter)
}
func increment(name string) {
defer wg.Done() // Schedule the call to Done to tell main we are done.
for range name {
atomic.AddInt32(&counter,1)
runtime.Gosched() // Yield the thread and be placed back in queue.
}
}
的 AddInt32 通过强制每次只能执行一个goroutine并完成一次加法操作,atomic软件包中的function可以同步整数值的加法。当goroutine尝试调用任何原子函数时,它们会自动与所引用的变量同步。
运行上面的程序时,您可以看到以下输出:
C:\彩票中心下载\goroutines>go run -race main.go
Counter: 15
C:\彩票中心下载\goroutines>
请注意,如果您替换代码行 原子.AddInt32(&counter,1) 与 计数器++,那么您将看到以下输出-
C:\彩票中心下载\goroutines>go run -race main.go
==================
WARNING: DATA RACE
Read at 0x0000006072b0 by goroutine 7:
main.increment()
C:/彩票中心下载/goroutines/main.go:31 +0x76
Previous write at 0x0000006072b0 by goroutine 8:
main.increment()
C:/彩票中心下载/goroutines/main.go:31 +0x90
Goroutine 7 (running) created at:
main.main()
C:/彩票中心下载/goroutines/main.go:18 +0x7e
Goroutine 8 (running) created at:
main.main()
C:/彩票中心下载/goroutines/main.go:19 +0x96
==================
Counter: 15
Found 1 data race(s)
exit status 66
C:\彩票中心下载\goroutines>