]> git.proxmox.com Git - rustc.git/blob - src/libstd/sync/mutex.rs
New upstream version 1.18.0+dfsg1
[rustc.git] / src / libstd / sync / mutex.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use cell::UnsafeCell;
12 use fmt;
13 use marker;
14 use mem;
15 use ops::{Deref, DerefMut};
16 use ptr;
17 use sys_common::mutex as sys;
18 use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
19
20 /// A mutual exclusion primitive useful for protecting shared data
21 ///
22 /// This mutex will block threads waiting for the lock to become available. The
23 /// mutex can also be statically initialized or created via a `new`
24 /// constructor. Each mutex has a type parameter which represents the data that
25 /// it is protecting. The data can only be accessed through the RAII guards
26 /// returned from `lock` and `try_lock`, which guarantees that the data is only
27 /// ever accessed when the mutex is locked.
28 ///
29 /// # Poisoning
30 ///
31 /// The mutexes in this module implement a strategy called "poisoning" where a
32 /// mutex is considered poisoned whenever a thread panics while holding the
33 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
34 /// data by default as it is likely tainted (some invariant is not being
35 /// upheld).
36 ///
37 /// For a mutex, this means that the `lock` and `try_lock` methods return a
38 /// `Result` which indicates whether a mutex has been poisoned or not. Most
39 /// usage of a mutex will simply `unwrap()` these results, propagating panics
40 /// among threads to ensure that a possibly invalid invariant is not witnessed.
41 ///
42 /// A poisoned mutex, however, does not prevent all access to the underlying
43 /// data. The `PoisonError` type has an `into_inner` method which will return
44 /// the guard that would have otherwise been returned on a successful lock. This
45 /// allows access to the data, despite the lock being poisoned.
46 ///
47 /// # Examples
48 ///
49 /// ```
50 /// use std::sync::{Arc, Mutex};
51 /// use std::thread;
52 /// use std::sync::mpsc::channel;
53 ///
54 /// const N: usize = 10;
55 ///
56 /// // Spawn a few threads to increment a shared variable (non-atomically), and
57 /// // let the main thread know once all increments are done.
58 /// //
59 /// // Here we're using an Arc to share memory among threads, and the data inside
60 /// // the Arc is protected with a mutex.
61 /// let data = Arc::new(Mutex::new(0));
62 ///
63 /// let (tx, rx) = channel();
64 /// for _ in 0..N {
65 /// let (data, tx) = (data.clone(), tx.clone());
66 /// thread::spawn(move || {
67 /// // The shared state can only be accessed once the lock is held.
68 /// // Our non-atomic increment is safe because we're the only thread
69 /// // which can access the shared state when the lock is held.
70 /// //
71 /// // We unwrap() the return value to assert that we are not expecting
72 /// // threads to ever fail while holding the lock.
73 /// let mut data = data.lock().unwrap();
74 /// *data += 1;
75 /// if *data == N {
76 /// tx.send(()).unwrap();
77 /// }
78 /// // the lock is unlocked here when `data` goes out of scope.
79 /// });
80 /// }
81 ///
82 /// rx.recv().unwrap();
83 /// ```
84 ///
85 /// To recover from a poisoned mutex:
86 ///
87 /// ```
88 /// use std::sync::{Arc, Mutex};
89 /// use std::thread;
90 ///
91 /// let lock = Arc::new(Mutex::new(0_u32));
92 /// let lock2 = lock.clone();
93 ///
94 /// let _ = thread::spawn(move || -> () {
95 /// // This thread will acquire the mutex first, unwrapping the result of
96 /// // `lock` because the lock has not been poisoned.
97 /// let _guard = lock2.lock().unwrap();
98 ///
99 /// // This panic while holding the lock (`_guard` is in scope) will poison
100 /// // the mutex.
101 /// panic!();
102 /// }).join();
103 ///
104 /// // The lock is poisoned by this point, but the returned result can be
105 /// // pattern matched on to return the underlying guard on both branches.
106 /// let mut guard = match lock.lock() {
107 /// Ok(guard) => guard,
108 /// Err(poisoned) => poisoned.into_inner(),
109 /// };
110 ///
111 /// *guard += 1;
112 /// ```
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub struct Mutex<T: ?Sized> {
115 // Note that this mutex is in a *box*, not inlined into the struct itself.
116 // Once a native mutex has been used once, its address can never change (it
117 // can't be moved). This mutex type can be safely moved at any time, so to
118 // ensure that the native mutex is used correctly we box the inner mutex to
119 // give it a constant address.
120 inner: Box<sys::Mutex>,
121 poison: poison::Flag,
122 data: UnsafeCell<T>,
123 }
124
125 // these are the only places where `T: Send` matters; all other
126 // functionality works fine on a single thread.
127 #[stable(feature = "rust1", since = "1.0.0")]
128 unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
129 #[stable(feature = "rust1", since = "1.0.0")]
130 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }
131
132 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
133 /// dropped (falls out of scope), the lock will be unlocked.
134 ///
135 /// The data protected by the mutex can be accessed through this guard via its
136 /// [`Deref`] and [`DerefMut`] implementations.
137 ///
138 /// This structure is created by the [`lock`] and [`try_lock`] methods on
139 /// [`Mutex`].
140 ///
141 /// [`Deref`]: ../../std/ops/trait.Deref.html
142 /// [`DerefMut`]: ../../std/ops/trait.DerefMut.html
143 /// [`lock`]: struct.Mutex.html#method.lock
144 /// [`try_lock`]: struct.Mutex.html#method.try_lock
145 /// [`Mutex`]: struct.Mutex.html
146 #[must_use]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct MutexGuard<'a, T: ?Sized + 'a> {
149 // funny underscores due to how Deref/DerefMut currently work (they
150 // disregard field privacy).
151 __lock: &'a Mutex<T>,
152 __poison: poison::Guard,
153 }
154
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<'a, T: ?Sized> !marker::Send for MutexGuard<'a, T> {}
157
158 impl<T> Mutex<T> {
159 /// Creates a new mutex in an unlocked state ready for use.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use std::sync::Mutex;
165 ///
166 /// let mutex = Mutex::new(0);
167 /// ```
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub fn new(t: T) -> Mutex<T> {
170 let mut m = Mutex {
171 inner: box sys::Mutex::new(),
172 poison: poison::Flag::new(),
173 data: UnsafeCell::new(t),
174 };
175 unsafe {
176 m.inner.init();
177 }
178 m
179 }
180 }
181
182 impl<T: ?Sized> Mutex<T> {
183 /// Acquires a mutex, blocking the current thread until it is able to do so.
184 ///
185 /// This function will block the local thread until it is available to acquire
186 /// the mutex. Upon returning, the thread is the only thread with the lock
187 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
188 /// the guard goes out of scope, the mutex will be unlocked.
189 ///
190 /// The exact behavior on locking a mutex in the thread which already holds
191 /// the lock is left unspecified. However, this function will not return on
192 /// the second call (it might panic or deadlock, for example).
193 ///
194 /// # Errors
195 ///
196 /// If another user of this mutex panicked while holding the mutex, then
197 /// this call will return an error once the mutex is acquired.
198 ///
199 /// # Panics
200 ///
201 /// This function might panic when called if the lock is already held by
202 /// the current thread.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use std::sync::{Arc, Mutex};
208 /// use std::thread;
209 ///
210 /// let mutex = Arc::new(Mutex::new(0));
211 /// let c_mutex = mutex.clone();
212 ///
213 /// thread::spawn(move || {
214 /// *c_mutex.lock().unwrap() = 10;
215 /// }).join().expect("thread::spawn failed");
216 /// assert_eq!(*mutex.lock().unwrap(), 10);
217 /// ```
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn lock(&self) -> LockResult<MutexGuard<T>> {
220 unsafe {
221 self.inner.lock();
222 MutexGuard::new(self)
223 }
224 }
225
226 /// Attempts to acquire this lock.
227 ///
228 /// If the lock could not be acquired at this time, then `Err` is returned.
229 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
230 /// guard is dropped.
231 ///
232 /// This function does not block.
233 ///
234 /// # Errors
235 ///
236 /// If another user of this mutex panicked while holding the mutex, then
237 /// this call will return failure if the mutex would otherwise be
238 /// acquired.
239 ///
240 /// # Examples
241 ///
242 /// ```
243 /// use std::sync::{Arc, Mutex};
244 /// use std::thread;
245 ///
246 /// let mutex = Arc::new(Mutex::new(0));
247 /// let c_mutex = mutex.clone();
248 ///
249 /// thread::spawn(move || {
250 /// let mut lock = c_mutex.try_lock();
251 /// if let Ok(ref mut mutex) = lock {
252 /// **mutex = 10;
253 /// } else {
254 /// println!("try_lock failed");
255 /// }
256 /// }).join().expect("thread::spawn failed");
257 /// assert_eq!(*mutex.lock().unwrap(), 10);
258 /// ```
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
261 unsafe {
262 if self.inner.try_lock() {
263 Ok(MutexGuard::new(self)?)
264 } else {
265 Err(TryLockError::WouldBlock)
266 }
267 }
268 }
269
270 /// Determines whether the mutex is poisoned.
271 ///
272 /// If another thread is active, the mutex can still become poisoned at any
273 /// time. You should not trust a `false` value for program correctness
274 /// without additional synchronization.
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use std::sync::{Arc, Mutex};
280 /// use std::thread;
281 ///
282 /// let mutex = Arc::new(Mutex::new(0));
283 /// let c_mutex = mutex.clone();
284 ///
285 /// let _ = thread::spawn(move || {
286 /// let _lock = c_mutex.lock().unwrap();
287 /// panic!(); // the mutex gets poisoned
288 /// }).join();
289 /// assert_eq!(mutex.is_poisoned(), true);
290 /// ```
291 #[inline]
292 #[stable(feature = "sync_poison", since = "1.2.0")]
293 pub fn is_poisoned(&self) -> bool {
294 self.poison.get()
295 }
296
297 /// Consumes this mutex, returning the underlying data.
298 ///
299 /// # Errors
300 ///
301 /// If another user of this mutex panicked while holding the mutex, then
302 /// this call will return an error instead.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// use std::sync::Mutex;
308 ///
309 /// let mutex = Mutex::new(0);
310 /// assert_eq!(mutex.into_inner().unwrap(), 0);
311 /// ```
312 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
313 pub fn into_inner(self) -> LockResult<T> where T: Sized {
314 // We know statically that there are no outstanding references to
315 // `self` so there's no need to lock the inner mutex.
316 //
317 // To get the inner value, we'd like to call `data.into_inner()`,
318 // but because `Mutex` impl-s `Drop`, we can't move out of it, so
319 // we'll have to destructure it manually instead.
320 unsafe {
321 // Like `let Mutex { inner, poison, data } = self`.
322 let (inner, poison, data) = {
323 let Mutex { ref inner, ref poison, ref data } = self;
324 (ptr::read(inner), ptr::read(poison), ptr::read(data))
325 };
326 mem::forget(self);
327 inner.destroy(); // Keep in sync with the `Drop` impl.
328 drop(inner);
329
330 poison::map_result(poison.borrow(), |_| data.into_inner())
331 }
332 }
333
334 /// Returns a mutable reference to the underlying data.
335 ///
336 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
337 /// take place---the mutable borrow statically guarantees no locks exist.
338 ///
339 /// # Errors
340 ///
341 /// If another user of this mutex panicked while holding the mutex, then
342 /// this call will return an error instead.
343 ///
344 /// # Examples
345 ///
346 /// ```
347 /// use std::sync::Mutex;
348 ///
349 /// let mut mutex = Mutex::new(0);
350 /// *mutex.get_mut().unwrap() = 10;
351 /// assert_eq!(*mutex.lock().unwrap(), 10);
352 /// ```
353 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
354 pub fn get_mut(&mut self) -> LockResult<&mut T> {
355 // We know statically that there are no other references to `self`, so
356 // there's no need to lock the inner mutex.
357 let data = unsafe { &mut *self.data.get() };
358 poison::map_result(self.poison.borrow(), |_| data )
359 }
360 }
361
362 #[stable(feature = "rust1", since = "1.0.0")]
363 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
364 fn drop(&mut self) {
365 // This is actually safe b/c we know that there is no further usage of
366 // this mutex (it's up to the user to arrange for a mutex to get
367 // dropped, that's not our job)
368 //
369 // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
370 unsafe { self.inner.destroy() }
371 }
372 }
373
374 #[stable(feature = "mutex_default", since = "1.9.0")]
375 impl<T: ?Sized + Default> Default for Mutex<T> {
376 /// Creates a `Mutex<T>`, with the `Default` value for T.
377 fn default() -> Mutex<T> {
378 Mutex::new(Default::default())
379 }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385 match self.try_lock() {
386 Ok(guard) => write!(f, "Mutex {{ data: {:?} }}", &*guard),
387 Err(TryLockError::Poisoned(err)) => {
388 write!(f, "Mutex {{ data: Poisoned({:?}) }}", &**err.get_ref())
389 },
390 Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}")
391 }
392 }
393 }
394
395 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
396 unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
397 poison::map_result(lock.poison.borrow(), |guard| {
398 MutexGuard {
399 __lock: lock,
400 __poison: guard,
401 }
402 })
403 }
404 }
405
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> {
408 type Target = T;
409
410 fn deref(&self) -> &T {
411 unsafe { &*self.__lock.data.get() }
412 }
413 }
414
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> {
417 fn deref_mut(&mut self) -> &mut T {
418 unsafe { &mut *self.__lock.data.get() }
419 }
420 }
421
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
424 #[inline]
425 fn drop(&mut self) {
426 unsafe {
427 self.__lock.poison.done(&self.__poison);
428 self.__lock.inner.unlock();
429 }
430 }
431 }
432
433 #[stable(feature = "std_debug", since = "1.16.0")]
434 impl<'a, T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'a, T> {
435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
436 f.debug_struct("MutexGuard")
437 .field("lock", &self.__lock)
438 .finish()
439 }
440 }
441
442 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
443 &guard.__lock.inner
444 }
445
446 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
447 &guard.__lock.poison
448 }
449
450 #[cfg(all(test, not(target_os = "emscripten")))]
451 mod tests {
452 use sync::mpsc::channel;
453 use sync::{Arc, Mutex, Condvar};
454 use sync::atomic::{AtomicUsize, Ordering};
455 use thread;
456
457 struct Packet<T>(Arc<(Mutex<T>, Condvar)>);
458
459 #[derive(Eq, PartialEq, Debug)]
460 struct NonCopy(i32);
461
462 unsafe impl<T: Send> Send for Packet<T> {}
463 unsafe impl<T> Sync for Packet<T> {}
464
465 #[test]
466 fn smoke() {
467 let m = Mutex::new(());
468 drop(m.lock().unwrap());
469 drop(m.lock().unwrap());
470 }
471
472 #[test]
473 fn lots_and_lots() {
474 const J: u32 = 1000;
475 const K: u32 = 3;
476
477 let m = Arc::new(Mutex::new(0));
478
479 fn inc(m: &Mutex<u32>) {
480 for _ in 0..J {
481 *m.lock().unwrap() += 1;
482 }
483 }
484
485 let (tx, rx) = channel();
486 for _ in 0..K {
487 let tx2 = tx.clone();
488 let m2 = m.clone();
489 thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); });
490 let tx2 = tx.clone();
491 let m2 = m.clone();
492 thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); });
493 }
494
495 drop(tx);
496 for _ in 0..2 * K {
497 rx.recv().unwrap();
498 }
499 assert_eq!(*m.lock().unwrap(), J * K * 2);
500 }
501
502 #[test]
503 fn try_lock() {
504 let m = Mutex::new(());
505 *m.try_lock().unwrap() = ();
506 }
507
508 #[test]
509 fn test_into_inner() {
510 let m = Mutex::new(NonCopy(10));
511 assert_eq!(m.into_inner().unwrap(), NonCopy(10));
512 }
513
514 #[test]
515 fn test_into_inner_drop() {
516 struct Foo(Arc<AtomicUsize>);
517 impl Drop for Foo {
518 fn drop(&mut self) {
519 self.0.fetch_add(1, Ordering::SeqCst);
520 }
521 }
522 let num_drops = Arc::new(AtomicUsize::new(0));
523 let m = Mutex::new(Foo(num_drops.clone()));
524 assert_eq!(num_drops.load(Ordering::SeqCst), 0);
525 {
526 let _inner = m.into_inner().unwrap();
527 assert_eq!(num_drops.load(Ordering::SeqCst), 0);
528 }
529 assert_eq!(num_drops.load(Ordering::SeqCst), 1);
530 }
531
532 #[test]
533 fn test_into_inner_poison() {
534 let m = Arc::new(Mutex::new(NonCopy(10)));
535 let m2 = m.clone();
536 let _ = thread::spawn(move || {
537 let _lock = m2.lock().unwrap();
538 panic!("test panic in inner thread to poison mutex");
539 }).join();
540
541 assert!(m.is_poisoned());
542 match Arc::try_unwrap(m).unwrap().into_inner() {
543 Err(e) => assert_eq!(e.into_inner(), NonCopy(10)),
544 Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x),
545 }
546 }
547
548 #[test]
549 fn test_get_mut() {
550 let mut m = Mutex::new(NonCopy(10));
551 *m.get_mut().unwrap() = NonCopy(20);
552 assert_eq!(m.into_inner().unwrap(), NonCopy(20));
553 }
554
555 #[test]
556 fn test_get_mut_poison() {
557 let m = Arc::new(Mutex::new(NonCopy(10)));
558 let m2 = m.clone();
559 let _ = thread::spawn(move || {
560 let _lock = m2.lock().unwrap();
561 panic!("test panic in inner thread to poison mutex");
562 }).join();
563
564 assert!(m.is_poisoned());
565 match Arc::try_unwrap(m).unwrap().get_mut() {
566 Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)),
567 Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x),
568 }
569 }
570
571 #[test]
572 fn test_mutex_arc_condvar() {
573 let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
574 let packet2 = Packet(packet.0.clone());
575 let (tx, rx) = channel();
576 let _t = thread::spawn(move|| {
577 // wait until parent gets in
578 rx.recv().unwrap();
579 let &(ref lock, ref cvar) = &*packet2.0;
580 let mut lock = lock.lock().unwrap();
581 *lock = true;
582 cvar.notify_one();
583 });
584
585 let &(ref lock, ref cvar) = &*packet.0;
586 let mut lock = lock.lock().unwrap();
587 tx.send(()).unwrap();
588 assert!(!*lock);
589 while !*lock {
590 lock = cvar.wait(lock).unwrap();
591 }
592 }
593
594 #[test]
595 fn test_arc_condvar_poison() {
596 let packet = Packet(Arc::new((Mutex::new(1), Condvar::new())));
597 let packet2 = Packet(packet.0.clone());
598 let (tx, rx) = channel();
599
600 let _t = thread::spawn(move || -> () {
601 rx.recv().unwrap();
602 let &(ref lock, ref cvar) = &*packet2.0;
603 let _g = lock.lock().unwrap();
604 cvar.notify_one();
605 // Parent should fail when it wakes up.
606 panic!();
607 });
608
609 let &(ref lock, ref cvar) = &*packet.0;
610 let mut lock = lock.lock().unwrap();
611 tx.send(()).unwrap();
612 while *lock == 1 {
613 match cvar.wait(lock) {
614 Ok(l) => {
615 lock = l;
616 assert_eq!(*lock, 1);
617 }
618 Err(..) => break,
619 }
620 }
621 }
622
623 #[test]
624 fn test_mutex_arc_poison() {
625 let arc = Arc::new(Mutex::new(1));
626 assert!(!arc.is_poisoned());
627 let arc2 = arc.clone();
628 let _ = thread::spawn(move|| {
629 let lock = arc2.lock().unwrap();
630 assert_eq!(*lock, 2);
631 }).join();
632 assert!(arc.lock().is_err());
633 assert!(arc.is_poisoned());
634 }
635
636 #[test]
637 fn test_mutex_arc_nested() {
638 // Tests nested mutexes and access
639 // to underlying data.
640 let arc = Arc::new(Mutex::new(1));
641 let arc2 = Arc::new(Mutex::new(arc));
642 let (tx, rx) = channel();
643 let _t = thread::spawn(move|| {
644 let lock = arc2.lock().unwrap();
645 let lock2 = lock.lock().unwrap();
646 assert_eq!(*lock2, 1);
647 tx.send(()).unwrap();
648 });
649 rx.recv().unwrap();
650 }
651
652 #[test]
653 fn test_mutex_arc_access_in_unwind() {
654 let arc = Arc::new(Mutex::new(1));
655 let arc2 = arc.clone();
656 let _ = thread::spawn(move|| -> () {
657 struct Unwinder {
658 i: Arc<Mutex<i32>>,
659 }
660 impl Drop for Unwinder {
661 fn drop(&mut self) {
662 *self.i.lock().unwrap() += 1;
663 }
664 }
665 let _u = Unwinder { i: arc2 };
666 panic!();
667 }).join();
668 let lock = arc.lock().unwrap();
669 assert_eq!(*lock, 2);
670 }
671
672 #[test]
673 fn test_mutex_unsized() {
674 let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
675 {
676 let b = &mut *mutex.lock().unwrap();
677 b[0] = 4;
678 b[2] = 5;
679 }
680 let comp: &[i32] = &[4, 2, 5];
681 assert_eq!(&*mutex.lock().unwrap(), comp);
682 }
683 }