New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: sync: add method Mutex.Locked(func()) #49563
Comments
Locked(func())
I think there are advantages to making this a function that takes a Locker rather than a method on Mutex. This would allow using it with either end of an RWMutex, or another custom Locker. |
// withLock runs while holding lk.
func withLock(lk sync.Locker, fn func()) {
lk.Lock()
defer lk.Unlock() // in case fn panics
fn()
} |
I'm not sure I would actually want to use the new API as it would increase indentation (at least for anonymous functions) and decrease readability. Additional counter arg is that one can already write this code as package level function today. |
In general we try not to have two different ways to do something, and for better or worse we have the current idioms. |
This proposal has been added to the active column of the proposals project |
Now that we have generics on the way, I would rather see us move in a direction that also eliminates unlocked-access bugs, not just incrementally update Perhaps a typed package sync
type Synchronized[T any] struct {
mu Mutex
val T
}
func (s *Synchronizedf[T]) Do(fn func(*T)) {
m.mu.Lock()
defer m.mu.Unlock()
fn(&m.val)
} (However, an API like the above probably ought to be prototyped and tested outside of the standard library to check its ergonomics.) |
Based on the discussion above, this proposal seems like a likely decline. |
No change in consensus, so declined. |
I'm raising this proposal to have the discussion once. There are alternatives that exist today, but I figure this may be worth considering. I could not find a similar proposal in the backlog of open nor closed issues (no results for scoped mutex, nor sync locked).
I propose to add
sync.Mutex.Locked(func())
:Benefits
defer
to unlock.Locked
to handle their synchronization, rather than embeddingLock / defer Unlock
into the top of many functions.BenchmarkUgly
in the play link below).Locked
and handle the result outside the lock/unlock paths.Downsides
sync.Mutex
, whereas the current implementation is a strictly to the point mutex.Locked
function cannot be inlined, and neither can the function passed to it. Theoretically this slowness can be eliminated.Code example / benchmarks
https://play.golang.org/p/Tll9rFTuPUM
The text was updated successfully, but these errors were encountered: