File tree Expand file tree Collapse file tree 2 files changed +20
-7
lines changed
Expand file tree Collapse file tree 2 files changed +20
-7
lines changed Original file line number Diff line number Diff line change 11use std:: cell:: UnsafeCell ;
22use std:: fmt;
3+ use std:: future:: Future ;
34use std:: ops:: { Deref , DerefMut } ;
45use std:: process;
56use std:: sync:: atomic:: { AtomicUsize , Ordering } ;
@@ -263,6 +264,14 @@ impl<T: ?Sized> Mutex<T> {
263264}
264265
265266impl < T : ?Sized > Mutex < T > {
267+ async fn lock_arc_impl ( self : Arc < Self > ) -> MutexGuardArc < T > {
268+ if let Some ( guard) = self . try_lock_arc ( ) {
269+ return guard;
270+ }
271+ self . acquire_slow ( ) . await ;
272+ MutexGuardArc ( self )
273+ }
274+
266275 /// Acquires the mutex and clones a reference to it.
267276 ///
268277 /// Returns an owned guard that releases the mutex when dropped.
@@ -280,12 +289,8 @@ impl<T: ?Sized> Mutex<T> {
280289 /// # })
281290 /// ```
282291 #[ inline]
283- pub async fn lock_arc ( self : & Arc < Self > ) -> MutexGuardArc < T > {
284- if let Some ( guard) = self . try_lock_arc ( ) {
285- return guard;
286- }
287- self . acquire_slow ( ) . await ;
288- MutexGuardArc ( self . clone ( ) )
292+ pub fn lock_arc ( self : & Arc < Self > ) -> impl Future < Output = MutexGuardArc < T > > {
293+ self . clone ( ) . lock_arc_impl ( )
289294 }
290295
291296 /// Attempts to acquire the mutex and clone a reference to it.
Original file line number Diff line number Diff line change 1- #[ cfg( not( target_arch = "wasm32" ) ) ]
21use std:: sync:: Arc ;
32#[ cfg( not( target_arch = "wasm32" ) ) ]
43use std:: thread;
@@ -76,3 +75,12 @@ fn contention() {
7675 assert_eq ! ( num_tasks, * lock) ;
7776 } ) ;
7877}
78+
79+ #[ test]
80+ fn lifetime ( ) {
81+ // Show that the future keeps the mutex alive.
82+ let _fut = {
83+ let mutex = Arc :: new ( Mutex :: new ( 0i32 ) ) ;
84+ mutex. lock_arc ( )
85+ } ;
86+ }
You can’t perform that action at this time.
0 commit comments