go - 没有互斥锁的 Go 协程
问题描述
在写入共享资源时运行没有任何互斥锁的 goroutines 时,我没有收到任何预期的运行时错误。相反,我得到了这个输出。正在写入共享资源的 goroutine 的输出没有被打印。但是当我运行时,go run .
我可以看到运行时错误。为什么会这样?
编辑:我注意到如果我构建可执行文件然后运行它,我不会遇到运行时错误。但如果我使用go run .
.
GOROOT=C:\Go #gosetup
GOPATH=C:\Users\vtimo\go #gosetup
C:\Go\bin\go.exe build -i -o C:\Users\vtimo\Projects\go-concurrency\src\go_build_main_go_book_go.exe C:\Users\vtimo\Projects\go-concurrency\main.go C:\Users\vtimo\Projects\go-concurrency\book.go #gosetup
C:\Users\vtimo\Projects\go-concurrency\src\go_build_main_go_book_go.exe #gosetup
from database
from database
Title: "The Android's Dream"
Author: "John Scalzi"
Published: 2006
from database
Title: "The Hobbit"
Author: "J.R.R. Tolkien"
Published: 1937
from database
Title: "On Basilisk Station"
Author: "David Weber"
Published: 1993
from database
Title: "The Hobbit"
Author: "J.R.R. Tolkien"
Published: 1937
from database
Title: "On Basilisk Station"
Author: "David Weber"
Published: 1993
from database
Title: "The Gods Themselves"
Author: "Isaac Asimov"
Published: 1973
from database
Title: "A Tale of Two Cities"
Author: "Charles Dickens"
Published: 1859
Title: "The Gods Themselves"
Author: "Isaac Asimov"
Published: 1973
from database
Title: "I, Robot"
Author: "Isaac Asimov"
Published: 1950
from database
Title: "The Hitchhiker's Guide to the Galaxy"
Author: "Douglas Adams"
Published: 1979
Process finished with exit code 0
源代码:
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var cache = map[int]Book{}
var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
func main() {
wg := &sync.WaitGroup{}
for i := 0; i < 10; i++ {
id := rnd.Intn(10) + 1
wg.Add(2)
go func(id int, group *sync.WaitGroup) {
if b, ok := queryCache(id); ok {
fmt.Println("from cache")
fmt.Println(b)
}
wg.Done()
}(id, wg)
go func(id int, group *sync.WaitGroup) {
if b, ok := queryDatabase(id); ok {
fmt.Println("from database")
fmt.Println(b)
}
wg.Done()
}(id, wg)
}
wg.Wait()
}
func queryCache(id int) (Book, bool) {
b, ok := cache[id]
return b, ok
}
func queryDatabase(id int) (Book, bool) {
time.Sleep(100 * time.Millisecond)
for _, b := range books {
if b.ID == id {
cache[id] = b
return b, true
}
}
return Book{}, false
}
解决方案
您可以使用-race
标志来检查是否有任何竞争条件:
例子:go run -race programfile.go
推荐阅读
- webgl - 使用大比例因子调整图像大小
- visual-studio-2017 - Visual Studio 2017 创建拉取请求按钮随机消失
- c# - 无法转换类型异常的对象
- r - 如何使用公开数据将字符串转换为 R 中的数值
- javascript - 从单页转换为多页应用程序后未加载数据
- javascript - 使用 React Native 运行繁重的 JS 任务
- dart - 用画布理解动画
- xamarin - 如何更改 Xamarin Forms 中的文本颜色状态栏?
- vb.net - 带有 DataGridView 的 VB .net
- python - 如何检查python中最长的子字符串