gpt4 book ai didi

go - 最简单的 Go 竞争条件示例?

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:39 25 4
gpt4 key购买 nike

我需要一个简单的 Go 代码示例,它肯定会使程序进入竞争状态。

有什么想法吗?

最佳答案

原问题:

I need a simple Go code sample which will definitely run the program into an race-condition.


例如,

racer.go:

package main

import (
"time"
)

var count int

func race() {
count++
}

func main() {
go race()
go race()
time.Sleep(1 * time.Second)
}

输出:

$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00000052ccf8 by goroutine 6:
main.race()
/home/peter/gopath/src/racer.go:10 +0x3a

Previous write at 0x00000052ccf8 by goroutine 5:
main.race()
/home/peter/gopath/src/racer.go:10 +0x56

Goroutine 6 (running) created at:
main.main()
/home/peter/gopath/src/racer.go:15 +0x5a

Goroutine 5 (finished) created at:
main.main()
/home/peter/gopath/src/racer.go:14 +0x42
==================
Found 1 data race(s)
exit status 66
$

关于go - 最简单的 Go 竞争条件示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53328571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com