2019-11-27 18:29:00 +00:00
|
|
|
use crate::error::Error;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::fmt;
|
|
|
|
use crate::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use crate::thread;
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
|
2019-11-27 18:29:00 +00:00
|
|
|
pub struct Flag {
|
|
|
|
failed: AtomicBool,
|
|
|
|
}
|
2015-02-20 20:00:26 +00:00
|
|
|
|
2016-07-07 18:46:09 +00:00
|
|
|
// Note that the Ordering uses to access the `failed` field of `Flag` below is
|
|
|
|
// always `Relaxed`, and that's because this isn't actually protecting any data,
|
|
|
|
// it's just a flag whether we've panicked or not.
|
|
|
|
//
|
|
|
|
// The actual location that this matters is when a mutex is **locked** which is
|
|
|
|
// where we have external synchronization ensuring that we see memory
|
|
|
|
// reads/writes to this flag.
|
|
|
|
//
|
|
|
|
// As a result, if it matters, we should see the correct value for `failed` in
|
|
|
|
// all cases.
|
2015-02-20 20:00:26 +00:00
|
|
|
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
impl Flag {
|
2015-05-27 08:18:36 +00:00
|
|
|
pub const fn new() -> Flag {
|
2016-07-07 18:46:09 +00:00
|
|
|
Flag { failed: AtomicBool::new(false) }
|
2015-05-27 08:18:36 +00:00
|
|
|
}
|
|
|
|
|
2014-12-09 04:20:03 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn borrow(&self) -> LockResult<Guard> {
|
2015-02-17 23:10:25 +00:00
|
|
|
let ret = Guard { panicking: thread::panicking() };
|
2019-11-27 18:29:00 +00:00
|
|
|
if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn done(&self, guard: &Guard) {
|
2015-02-17 23:10:25 +00:00
|
|
|
if !guard.panicking && thread::panicking() {
|
2016-07-07 18:46:09 +00:00
|
|
|
self.failed.store(true, Ordering::Relaxed);
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn get(&self) -> bool {
|
2016-07-07 18:46:09 +00:00
|
|
|
self.failed.load(Ordering::Relaxed)
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-09 04:20:03 +00:00
|
|
|
pub struct Guard {
|
2014-12-07 02:34:37 +00:00
|
|
|
panicking: bool,
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
}
|
|
|
|
|
2014-12-09 04:20:03 +00:00
|
|
|
/// A type of error which can be returned whenever a lock is acquired.
|
|
|
|
///
|
2017-02-24 19:56:04 +00:00
|
|
|
/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
|
2014-12-09 04:20:03 +00:00
|
|
|
/// is held. The precise semantics for when a lock is poisoned is documented on
|
|
|
|
/// each lock, but once a lock is poisoned then all future acquisitions will
|
|
|
|
/// return this error.
|
2017-02-24 19:56:04 +00:00
|
|
|
///
|
2017-09-23 22:28:08 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::sync::{Arc, Mutex};
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let mutex = Arc::new(Mutex::new(1));
|
|
|
|
///
|
|
|
|
/// // poison the mutex
|
|
|
|
/// let c_mutex = mutex.clone();
|
|
|
|
/// let _ = thread::spawn(move || {
|
|
|
|
/// let mut data = c_mutex.lock().unwrap();
|
|
|
|
/// *data = 2;
|
|
|
|
/// panic!();
|
|
|
|
/// }).join();
|
|
|
|
///
|
|
|
|
/// match mutex.lock() {
|
|
|
|
/// Ok(_) => unreachable!(),
|
|
|
|
/// Err(p_err) => {
|
|
|
|
/// let data = p_err.get_ref();
|
|
|
|
/// println!("recovered: {}", data);
|
|
|
|
/// }
|
|
|
|
/// };
|
|
|
|
/// ```
|
|
|
|
///
|
2017-02-24 19:56:04 +00:00
|
|
|
/// [`Mutex`]: ../../std/sync/struct.Mutex.html
|
|
|
|
/// [`RwLock`]: ../../std/sync/struct.RwLock.html
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-09 04:20:03 +00:00
|
|
|
pub struct PoisonError<T> {
|
|
|
|
guard: T,
|
|
|
|
}
|
|
|
|
|
2017-09-23 22:28:08 +00:00
|
|
|
/// An enumeration of possible errors associated with a [`TryLockResult`] which
|
2018-02-16 14:56:50 +00:00
|
|
|
/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
|
2017-09-23 22:28:08 +00:00
|
|
|
/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
|
2017-04-04 03:32:59 +00:00
|
|
|
///
|
2017-09-23 22:28:08 +00:00
|
|
|
/// [`Mutex`]: struct.Mutex.html
|
|
|
|
/// [`RwLock`]: struct.RwLock.html
|
|
|
|
/// [`TryLockResult`]: type.TryLockResult.html
|
2017-04-04 03:32:59 +00:00
|
|
|
/// [`try_lock`]: struct.Mutex.html#method.try_lock
|
2017-09-23 22:28:08 +00:00
|
|
|
/// [`try_read`]: struct.RwLock.html#method.try_read
|
|
|
|
/// [`try_write`]: struct.RwLock.html#method.try_write
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-09 04:20:03 +00:00
|
|
|
pub enum TryLockError<T> {
|
2015-05-08 15:12:29 +00:00
|
|
|
/// The lock could not be acquired because another thread failed while holding
|
2014-12-09 04:20:03 +00:00
|
|
|
/// the lock.
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-02-20 00:08:36 +00:00
|
|
|
Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
|
2014-12-09 04:20:03 +00:00
|
|
|
/// The lock could not be acquired at this time because the operation would
|
|
|
|
/// otherwise block.
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-09 04:20:03 +00:00
|
|
|
WouldBlock,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A type alias for the result of a lock method which can be poisoned.
|
|
|
|
///
|
2017-02-24 19:56:04 +00:00
|
|
|
/// The [`Ok`] variant of this result indicates that the primitive was not
|
|
|
|
/// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
|
|
|
|
/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
|
|
|
|
/// the associated guard, and it can be acquired through the [`into_inner`]
|
2014-12-09 04:20:03 +00:00
|
|
|
/// method.
|
2017-02-24 19:56:04 +00:00
|
|
|
///
|
|
|
|
/// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
|
|
|
|
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
|
2017-09-16 01:52:40 +00:00
|
|
|
/// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-09 04:20:03 +00:00
|
|
|
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
|
|
|
|
|
|
|
|
/// A type alias for the result of a nonblocking locking method.
|
|
|
|
///
|
2017-02-24 19:56:04 +00:00
|
|
|
/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
|
|
|
|
/// necessarily hold the associated guard in the [`Err`] type as the lock may not
|
2014-12-09 04:20:03 +00:00
|
|
|
/// have been acquired for other reasons.
|
2017-02-24 19:56:04 +00:00
|
|
|
///
|
|
|
|
/// [`LockResult`]: ../../std/sync/type.LockResult.html
|
|
|
|
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-09 04:20:03 +00:00
|
|
|
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
|
|
|
|
|
2015-01-26 03:03:10 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-01-23 18:38:50 +00:00
|
|
|
impl<T> fmt::Debug for PoisonError<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-01-23 18:38:50 +00:00
|
|
|
"PoisonError { inner: .. }".fmt(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 17:15:42 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-01-20 23:45:07 +00:00
|
|
|
impl<T> fmt::Display for PoisonError<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-03-19 23:37:34 +00:00
|
|
|
"poisoned lock: another task failed inside".fmt(f)
|
2015-01-17 19:31:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 16:54:28 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-10-06 05:28:27 +00:00
|
|
|
impl<T> Error for PoisonError<T> {
|
2015-01-17 19:31:55 +00:00
|
|
|
fn description(&self) -> &str {
|
|
|
|
"poisoned lock: another task failed inside"
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> PoisonError<T> {
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Creates a `PoisonError`.
|
2017-02-24 19:56:04 +00:00
|
|
|
///
|
|
|
|
/// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
|
|
|
|
///
|
|
|
|
/// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
|
|
|
|
/// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
|
2015-06-11 01:43:08 +00:00
|
|
|
#[stable(feature = "sync_poison", since = "1.2.0")]
|
2015-01-23 19:58:49 +00:00
|
|
|
pub fn new(guard: T) -> PoisonError<T> {
|
2018-11-06 20:05:44 +00:00
|
|
|
PoisonError { guard }
|
2015-01-23 19:58:49 +00:00
|
|
|
}
|
|
|
|
|
2014-12-09 04:20:03 +00:00
|
|
|
/// Consumes this error indicating that a lock is poisoned, returning the
|
2015-01-14 05:24:26 +00:00
|
|
|
/// underlying guard to allow access regardless.
|
2017-09-23 22:28:08 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::collections::HashSet;
|
|
|
|
/// use std::sync::{Arc, Mutex};
|
|
|
|
/// use std::thread;
|
|
|
|
///
|
|
|
|
/// let mutex = Arc::new(Mutex::new(HashSet::new()));
|
|
|
|
///
|
|
|
|
/// // poison the mutex
|
|
|
|
/// let c_mutex = mutex.clone();
|
|
|
|
/// let _ = thread::spawn(move || {
|
|
|
|
/// let mut data = c_mutex.lock().unwrap();
|
|
|
|
/// data.insert(10);
|
|
|
|
/// panic!();
|
|
|
|
/// }).join();
|
|
|
|
///
|
|
|
|
/// let p_err = mutex.lock().unwrap_err();
|
|
|
|
/// let data = p_err.into_inner();
|
|
|
|
/// println!("recovered {} items", data.len());
|
|
|
|
/// ```
|
2015-06-11 01:43:08 +00:00
|
|
|
#[stable(feature = "sync_poison", since = "1.2.0")]
|
2019-11-27 18:29:00 +00:00
|
|
|
pub fn into_inner(self) -> T {
|
|
|
|
self.guard
|
|
|
|
}
|
2015-01-14 05:24:26 +00:00
|
|
|
|
|
|
|
/// Reaches into this error indicating that a lock is poisoned, returning a
|
|
|
|
/// reference to the underlying guard to allow access regardless.
|
2015-06-11 01:43:08 +00:00
|
|
|
#[stable(feature = "sync_poison", since = "1.2.0")]
|
2019-11-27 18:29:00 +00:00
|
|
|
pub fn get_ref(&self) -> &T {
|
|
|
|
&self.guard
|
|
|
|
}
|
2015-01-14 05:24:26 +00:00
|
|
|
|
|
|
|
/// Reaches into this error indicating that a lock is poisoned, returning a
|
|
|
|
/// mutable reference to the underlying guard to allow access regardless.
|
2015-06-11 01:43:08 +00:00
|
|
|
#[stable(feature = "sync_poison", since = "1.2.0")]
|
2019-11-27 18:29:00 +00:00
|
|
|
pub fn get_mut(&mut self) -> &mut T {
|
|
|
|
&mut self.guard
|
|
|
|
}
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
|
|
|
|
2015-11-16 16:54:28 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-03-31 00:56:48 +00:00
|
|
|
impl<T> From<PoisonError<T>> for TryLockError<T> {
|
|
|
|
fn from(err: PoisonError<T>) -> TryLockError<T> {
|
2014-12-09 04:20:03 +00:00
|
|
|
TryLockError::Poisoned(err)
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
}
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
|
2015-01-26 03:03:10 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-01-23 18:38:50 +00:00
|
|
|
impl<T> fmt::Debug for TryLockError<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-01-23 18:38:50 +00:00
|
|
|
match *self {
|
|
|
|
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
|
2019-11-27 18:29:00 +00:00
|
|
|
TryLockError::WouldBlock => "WouldBlock".fmt(f),
|
2015-01-23 18:38:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 17:15:42 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-02-12 01:24:57 +00:00
|
|
|
impl<T> fmt::Display for TryLockError<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2016-02-12 01:24:57 +00:00
|
|
|
match *self {
|
|
|
|
TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
|
2019-11-27 18:29:00 +00:00
|
|
|
TryLockError::WouldBlock => "try_lock failed because the operation would block",
|
|
|
|
}
|
|
|
|
.fmt(f)
|
2015-01-17 19:31:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 16:54:28 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-10-06 05:28:27 +00:00
|
|
|
impl<T> Error for TryLockError<T> {
|
2015-01-17 19:31:55 +00:00
|
|
|
fn description(&self) -> &str {
|
|
|
|
match *self {
|
|
|
|
TryLockError::Poisoned(ref p) => p.description(),
|
2019-11-27 18:29:00 +00:00
|
|
|
TryLockError::WouldBlock => "try_lock failed because the operation would block",
|
2015-01-17 19:31:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-10 18:35:36 +00:00
|
|
|
fn cause(&self) -> Option<&dyn Error> {
|
2014-12-09 04:20:03 +00:00
|
|
|
match *self {
|
2015-01-17 19:31:55 +00:00
|
|
|
TryLockError::Poisoned(ref p) => Some(p),
|
2019-11-27 18:29:00 +00:00
|
|
|
_ => None,
|
std: Rewrite the `sync` module
This commit is a reimplementation of `std::sync` to be based on the
system-provided primitives wherever possible. The previous implementation was
fundamentally built on top of channels, and as part of the runtime reform it has
become clear that this is not the level of abstraction that the standard level
should be providing. This rewrite aims to provide as thin of a shim as possible
on top of the system primitives in order to make them safe.
The overall interface of the `std::sync` module has in general not changed, but
there are a few important distinctions, highlighted below:
* The condition variable type, `Condvar`, has been separated out of a `Mutex`.
A condition variable is now an entirely separate type. This separation
benefits users who only use one mutex, and provides a clearer distinction of
who's responsible for managing condition variables (the application).
* All of `Condvar`, `Mutex`, and `RWLock` are now directly built on top of
system primitives rather than using a custom implementation. The `Once`,
`Barrier`, and `Semaphore` types are still built upon these abstractions of
the system primitives.
* The `Condvar`, `Mutex`, and `RWLock` types all have a new static type and
constant initializer corresponding to them. These are provided primarily for C
FFI interoperation, but are often useful to otherwise simply have a global
lock. The types, however, will leak memory unless `destroy()` is called on
them, which is clearly documented.
* The `Condvar` implementation for an `RWLock` write lock has been removed. This
may be added back in the future with a userspace implementation, but this
commit is focused on exposing the system primitives first.
* The fundamental architecture of this design is to provide two separate layers.
The first layer is that exposed by `sys_common` which is a cross-platform
bare-metal abstraction of the system synchronization primitives. No attempt is
made at making this layer safe, and it is quite unsafe to use! It is currently
not exported as part of the API of the standard library, but the stabilization
of the `sys` module will ensure that these will be exposed in time. The
purpose of this layer is to provide the core cross-platform abstractions if
necessary to implementors.
The second layer is the layer provided by `std::sync` which is intended to be
the thinnest possible layer on top of `sys_common` which is entirely safe to
use. There are a few concerns which need to be addressed when making these
system primitives safe:
* Once used, the OS primitives can never be **moved**. This means that they
essentially need to have a stable address. The static primitives use
`&'static self` to enforce this, and the non-static primitives all use a
`Box` to provide this guarantee.
* Poisoning is leveraged to ensure that invalid data is not accessible from
other tasks after one has panicked.
In addition to these overall blanket safety limitations, each primitive has a
few restrictions of its own:
* Mutexes and rwlocks can only be unlocked from the same thread that they
were locked by. This is achieved through RAII lock guards which cannot be
sent across threads.
* Mutexes and rwlocks can only be unlocked if they were previously locked.
This is achieved by not exposing an unlocking method.
* A condition variable can only be waited on with a locked mutex. This is
achieved by requiring a `MutexGuard` in the `wait()` method.
* A condition variable cannot be used concurrently with more than one mutex.
This is guaranteed by dynamically binding a condition variable to
precisely one mutex for its entire lifecycle. This restriction may be able
to be relaxed in the future (a mutex is unbound when no threads are
waiting on the condvar), but for now it is sufficient to guarantee safety.
* Condvars now support timeouts for their blocking operations. The
implementation for these operations is provided by the system.
Due to the modification of the `Condvar` API, removal of the `std::sync::mutex`
API, and reimplementation, this is a breaking change. Most code should be fairly
easy to port using the examples in the documentation of these primitives.
[breaking-change]
Closes #17094
Closes #18003
2014-11-24 19:16:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-12-09 04:20:03 +00:00
|
|
|
|
2019-11-27 18:29:00 +00:00
|
|
|
pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
|
|
|
|
where
|
|
|
|
F: FnOnce(T) -> U,
|
|
|
|
{
|
2014-12-09 04:20:03 +00:00
|
|
|
match result {
|
|
|
|
Ok(t) => Ok(f(t)),
|
2019-11-27 18:29:00 +00:00
|
|
|
Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
|
2014-12-09 04:20:03 +00:00
|
|
|
}
|
|
|
|
}
|