On Tuesday, April 14, 2020 at 7:38:44 AM UTC-4, Slawomir Pryczek wrote:
>
> Hi Guys, was wondering about some things related to multithread code.
>
> 2. For lazy initialization double-check pattern. I found on several 
> sources that it is safe, still race detector complains about data races 
> (which is correct because there is race, which is done on purpose) - 
> https://software.intel.com/en-us/node/506123
> And of course this code seems to be working as expected
>
> https://play.golang.org/p/gUzWHr-1K9H
>

It is a race. Your code may 'seem' safe, and it may always work correctly 
on some processor and Go version combinations. But it also might work *some 
of the time* on some processor and Go version combinations, but fail in 
unexpected and hard to debug ways other times. I always like to suggest 
reading Benign Data Races: What Could Possibly Go Wrong 
<https://software.intel.com/en-us/blogs/2013/01/06/benign-data-races-what-could-possibly-go-wrong>
 
in cases like this. (It is from the same site you reference.) 

Be very careful with concurrency. Just because you found "several sources 
that it is safe", does not mean that it is. Even if it is safe in the case 
the article sites, the devil is always in the details with concurrency. It 
may be safe in C++, with its memory model, and guarantees, but that does 
not necessarily mean it is safe in another language, such as Go. Also, the 
article you reference (https://software.intel.com/en-us/node/506123)  uses 
a *tbb::atomic<T*>*, which is not not a go type. In your example you use a 
*bool 
*instead. Details. Also, the documentation specifically says that the 
example in the article only works on Intel processors, so even in C++, it 
would be unsafe for that code to run on processors.

One final note on this kind of optimization. Sometimes the Go runtime or 
even standard libraries play such 'crazy games'. Do not be fooled, it is ok 
for them to do it, but not for us. The runtime and libraries are aware of 
what processor they are running on (if necessary), and are tied to a 
specific version of Go. If the language internals change in a way that 
breaks their 'crazy games', they can fix them at the same time. We do not 
have that luxury. 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/cdf346cc-ab71-4080-9022-f99f8e91e6c9%40googlegroups.com.

Reply via email to