1
Fork 0

Move boxing and mutex checking logic of condvar into sys_common.

This commit is contained in:
Mara Bos 2020-10-01 00:57:46 +02:00
parent f283d3f02c
commit a8c2d4fc3d
4 changed files with 57 additions and 80 deletions

View file

@ -2,10 +2,8 @@
mod tests;
use crate::fmt;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sync::{mutex, MutexGuard, PoisonError};
use crate::sys_common::condvar as sys;
use crate::sys_common::mutex as sys_mutex;
use crate::sys_common::poison::{self, LockResult};
use crate::time::{Duration, Instant};
@ -109,8 +107,7 @@ impl WaitTimeoutResult {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Condvar {
inner: Box<sys::Condvar>,
mutex: AtomicUsize,
inner: sys::Condvar,
}
impl Condvar {
@ -126,11 +123,7 @@ impl Condvar {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> Condvar {
let mut c = Condvar { inner: box sys::Condvar::new(), mutex: AtomicUsize::new(0) };
unsafe {
c.inner.init();
}
c
Condvar { inner: sys::Condvar::new() }
}
/// Blocks the current thread until this condition variable receives a
@ -192,7 +185,6 @@ impl Condvar {
pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
let poisoned = unsafe {
let lock = mutex::guard_lock(&guard);
self.verify(lock);
self.inner.wait(lock);
mutex::guard_poison(&guard).get()
};
@ -389,7 +381,6 @@ impl Condvar {
) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
let (poisoned, result) = unsafe {
let lock = mutex::guard_lock(&guard);
self.verify(lock);
let success = self.inner.wait_timeout(lock, dur);
(mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
};
@ -510,7 +501,7 @@ impl Condvar {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn notify_one(&self) {
unsafe { self.inner.notify_one() }
self.inner.notify_one()
}
/// Wakes up all blocked threads on this condvar.
@ -550,27 +541,7 @@ impl Condvar {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn notify_all(&self) {
unsafe { self.inner.notify_all() }
}
fn verify(&self, mutex: &sys_mutex::MovableMutex) {
let addr = mutex.raw() as *const _ as usize;
match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
// If we got out 0, then we have successfully bound the mutex to
// this cvar.
0 => {}
// If we get out a value that's the same as `addr`, then someone
// already beat us to the punch.
n if n == addr => {}
// Anything else and we're using more than one mutex on this cvar,
// which is currently disallowed.
_ => panic!(
"attempted to use a condition variable with two \
mutexes"
),
}
self.inner.notify_all()
}
}
@ -588,10 +559,3 @@ impl Default for Condvar {
Condvar::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Drop for Condvar {
fn drop(&mut self) {
unsafe { self.inner.destroy() }
}
}