On Mon, Aug 17, 2020 at 12:54 PM leo.b...@npo-data.nl < leo.bal...@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/CAGrdgiXv%3Di5JL6J-J14gx0FJvyNpsRPZjD7GL60Xrd0LJXBYFQ%40mail.gmail.com.