Playing Devil's Advocate: https://golang.org/ref/mem says:

> To serialize access, protect the data with channel operations or other 
synchronization primitives such as those in the sync 
<https://golang.org/pkg/sync/> and sync/atomic 
<https://golang.org/pkg/sync/atomic/> packages.

So it explicitly mentions sync/atomic but only mentions 
sync.Mutex and sync.RWMutex further in the text.


On Monday, August 17, 2020 at 1:06:08 PM UTC+2 jesper.lou...@gmail.com 
wrote:

> On Mon, Aug 17, 2020 at 12:54 PM leo.b...@npo-data.nl <
> leo.b...@npo-data.nl> wrote:
>
>> Thanks. So I take it this must be handled by the compiler when generating 
>> assembly.
>>
>>
> Yes. The compiler generally follows the Go Memory Model reference 
> specification: https://golang.org/ref/mem
>
>
>> E.g. A co-worker pointed out that you can avoid sync.Mutex by using this 
>> construct:
>>
>>         if !atomic.CompareAndSwapInt32(&s.myLock, 0, 1) {
>>                 fmt.Println("locked")
>>                 return
>>         }
>>         defer atomic.StoreInt32(&s.myLock, 0)
>>         processData()
>>
>> Would this synchronise memory?
>>
>>
> Going straight by the specification: no. You need to use a sync.Mutex.
>
> In practice, it might work on certain architectures, due to artifacts of 
> how that specific CPU is implemented. Don't rely on it. You are usually 
> better off using the standard primitives until you really need the added 
> speed of atomics, and then constrain those to a few places in the program. 
> Also, there are a lot of tricks you can play with mutexes to avoid lock 
> contention, so measure measure measure.
>
>

-- 
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/34089270-c021-44c6-92bd-7bb2ede7a6een%40googlegroups.com.

Reply via email to