-
Notifications
You must be signed in to change notification settings - Fork 24
OnceCell/Lock::try_insert() #276
Copy link
Copy link
Closed
Labels
ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)API Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard librariesA proposal to add or alter unstable APIs in the standard libraries
Metadata
Metadata
Assignees
Labels
ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)API Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard librariesA proposal to add or alter unstable APIs in the standard libraries
Type
Fields
Give feedbackNo fields configured for issues without a type.
Proposal
Problem statement
I would like to insert a value into a
OnceCell/Lockand get back a reference to it while also checking if the value was already set or not.Motivating examples or use cases
This can be useful in racy conditions, where different threads or
Futures are trying to assign to the sameOnceCell/Lock. The "loser" should be able to get the old and new value and determine if there is any difference or what that difference is.Solution sketch
Alternatives
This proposal offers an optimization, but it's perfectly possible to do this with the existing methods:
try_insert()would offer an optimized path that doesn't require an additionalunwrap().This method is currently available in
once_cell, which as far as I'm aware was the original inspiration forstd::cell::OnceCellandstd::sync::OnceLock.Links and related work
once_cell::unsync::OnceCell::try_insert()once_cell::sync::OnceCell::try_insert()