rust/library/std/tests/sync/reentrant_lock.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.1 KiB
Rust
Raw Normal View History

use std::cell::RefCell;
use std::sync::{Arc, ReentrantLock};
use std::thread;
#[test]
fn smoke() {
2023-03-28 10:10:53 +00:00
let l = ReentrantLock::new(());
{
2023-03-28 10:10:53 +00:00
let a = l.lock();
{
2023-03-28 10:10:53 +00:00
let b = l.lock();
{
2023-03-28 10:10:53 +00:00
let c = l.lock();
assert_eq!(*c, ());
}
assert_eq!(*b, ());
}
assert_eq!(*a, ());
}
}
#[test]
fn is_mutex() {
2023-03-28 10:10:53 +00:00
let l = Arc::new(ReentrantLock::new(RefCell::new(0)));
let l2 = l.clone();
let lock = l.lock();
let child = thread::spawn(move || {
2023-03-28 10:10:53 +00:00
let lock = l2.lock();
assert_eq!(*lock.borrow(), 4950);
});
for i in 0..100 {
2023-03-28 10:10:53 +00:00
let lock = l.lock();
*lock.borrow_mut() += i;
}
drop(lock);
child.join().unwrap();
}
#[test]
fn trylock_works() {
2023-03-28 10:10:53 +00:00
let l = Arc::new(ReentrantLock::new(()));
let l2 = l.clone();
let _lock = l.try_lock();
let _lock2 = l.try_lock();
thread::spawn(move || {
2023-03-28 10:10:53 +00:00
let lock = l2.try_lock();
assert!(lock.is_none());
})
.join()
.unwrap();
2023-03-28 10:10:53 +00:00
let _lock3 = l.try_lock();
}