Add get
, set
and replace
methods to Mutex
and RwLock
#485
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
I have observed that in many situations, the lifetime of lock guards obtained from
Mutex
andRwLock
are unnecessary extended. Most of the situations are single reads and single writes. Unnecessary extended mutex guard can cause bad performance or even deadlock. It could be better if we can provide convenient methods for these situations where extending lifetime of a mutex guard is unnecessary, we could potentially avoid some bugs or performance degenerates, also make the code easier to understand.Motivating examples or use cases
Using lock methods in a long expression
People might write something like:
This unnecessarily extends the lifetime of the mutex guard, it could be better to write:
By providing a
Mutex::get
method, we could potentially prevent some unintended misuses.Assigning to value inside a mutex
I have observed that many people would write this to assigning to a value inside a mutex:
People might not realize that assignment will call the destructor of the old value. So if the value have non-trivial destructors, we might want to run the destructor without locking the mutex, it could be better to write:
It is not easy to notice the hidden cost of the first one, and even if people realize that the second way is better for performance, they may still choose the first one because it is easier to write. By providing a
Mutex::set
method that implements the second behavior, it could be more easy for people to write pragmatic codes.Solution sketch
Add these methods to the standard library:
Alternatives
AtomicCell
, but it only supports loading fromCopy
types. Also people might not want to introduce third-party dependencies.MutexExt
andRwLockExt
to implement the methods above.Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: