Answer the question
In order to leave comments, you need to log in
Why is it written in the textbook that there is no Data Race, although in fact there is?
Hello!
Help clean up your head on Go and concurrency. I am reading a book by Donovan and Kernighan, where there is an example about a parallel non-blocking cache (part 9.7).
On this page, highlighted in yellow a sentence that confuses me: https://i.imgur.com/7XkoPh2.png
They say a mutex is not necessary . If you open the code itself , and assume that there are no mutexes, on line 34 we get the value from the hash table. Next, compare it to nil and create a new valueentry
, which is eventually written back to the hash table. At the same time, another goroutine is read from the hash table, which receives nil, and does exactly the same thing as the previous one (in this example, the author wanted to make sure that if one goroutine is calculating a heavy function, the other does not do the same, but waited for the goroutine-main to finish its work). It turns out that the write and read operations create a data race. Race detector says the same thing.
Code: https://pastebin.com/LMmj3vGn
Answer the question
In order to leave comments, you need to log in
Textbook old? In recent versions of Go, map is very fond of panicking at any incomprehensible situation.
Perhaps instead of a mutex and a map it will sometimes be more efficient https://golang.org/pkg/sync/#Map
The author is right, there really is no race condition after e := memo.cache[key] . But with one big but - GOMAXPROCS=1 (this was before go1.5), then we can easily get concurrent read-write + panic or undefined behavior.
Concurrency is a very complex thing. Rust solved this problem best of all, but it is painful to write in it.
The point is that it is not necessary to protect the reading of the entry value with a mutex.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question