Logo

Programming-Idioms

History of Idiom 33 > diff from v21 to v22

Edit summary for version 22 by programming-idioms.org:
[Go] It is more idiomatic to declare mutex as a value. +demoURL

Version 21

2016-03-29, 13:42:52

Version 22

2017-05-27, 12:03:21

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Imports
import "sync"
Imports
import "sync"
Code
lock := &sync.RWMutex{}

lock.Lock()
x = f(x)
lock.Unlock()
Code
var lock sync.RWMutex

lock.Lock()
x = f(x)
lock.Unlock()
Comments bubble
You need to lock whenever accessing x.
Comments bubble
You need to lock whenever accessing x.
Doc URL
https://golang.org/pkg/sync/
Doc URL
https://golang.org/pkg/sync/
Demo URL
https://play.golang.org/p/f5URkHrCqu