On Monday, 17 August 2020 11:54:55 UTC+1, leo.b...@npo-data.nl wrote:
>
> 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?
>

sync.atomic does synchronise memory, yes.

Indeed, the implementation of Mutex.Lock starts similarly to what you've 
written:
https://github.com/golang/go/blob/master/src/sync/mutex.go#L72

But it then takes a lot more care to avoid starvation, see comments at
https://github.com/golang/go/blob/master/src/sync/mutex.go#L42

In other words: you're better off using sync.Mutex if what you want is a 
mutex, rather than rolling your own.

-- 
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/ab2c3838-75bf-4430-a9ea-02be2de78e66o%40googlegroups.com.

Reply via email to