尽管在写入共享资源时运行我的goroutine时没有任何互斥体,但是我没有遇到任何预期的运行时错误。相反,我得到了这个输出。 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