mirror of
https://github.com/asterinas/asterinas.git
synced 2025-06-28 20:03:22 +00:00
Implement atomic wrapper for integer-like type
This commit is contained in:
committed by
Tate, Hongliang Tian
parent
a7cb71161d
commit
21fedd1b60
@ -1,43 +1,14 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use core::sync::atomic::{AtomicU8, Ordering};
|
||||
use core::sync::atomic::AtomicU8;
|
||||
|
||||
use atomic_integer_wrapper::define_atomic_version_of_integer_like_type;
|
||||
use int_to_c_enum::TryFromInt;
|
||||
|
||||
/// A `ThreadStatus` which can be safely shared between threads.
|
||||
#[derive(Debug)]
|
||||
pub struct AtomicThreadStatus(AtomicU8);
|
||||
|
||||
impl AtomicThreadStatus {
|
||||
/// Creates a new atomic status.
|
||||
pub fn new(status: ThreadStatus) -> Self {
|
||||
Self(AtomicU8::new(status as u8))
|
||||
}
|
||||
|
||||
/// Loads a value from the atomic status.
|
||||
pub fn load(&self, order: Ordering) -> ThreadStatus {
|
||||
ThreadStatus::try_from(self.0.load(order)).unwrap()
|
||||
}
|
||||
|
||||
/// Stores a value into the atomic status.
|
||||
pub fn store(&self, new_status: ThreadStatus, order: Ordering) {
|
||||
self.0.store(new_status as u8, order);
|
||||
}
|
||||
|
||||
/// Stores a value into the atomic status if the current value is the same as the `current` value.
|
||||
pub fn compare_exchange(
|
||||
&self,
|
||||
current: ThreadStatus,
|
||||
new: ThreadStatus,
|
||||
success: Ordering,
|
||||
failure: Ordering,
|
||||
) -> Result<ThreadStatus, ThreadStatus> {
|
||||
self.0
|
||||
.compare_exchange(current as u8, new as u8, success, failure)
|
||||
.map(|val| ThreadStatus::try_from(val).unwrap())
|
||||
.map_err(|val| ThreadStatus::try_from(val).unwrap())
|
||||
}
|
||||
}
|
||||
define_atomic_version_of_integer_like_type!(ThreadStatus, try_from = true, {
|
||||
#[derive(Debug)]
|
||||
pub struct AtomicThreadStatus(AtomicU8);
|
||||
});
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, TryFromInt)]
|
||||
#[repr(u8)]
|
||||
@ -61,3 +32,9 @@ impl ThreadStatus {
|
||||
*self == ThreadStatus::Stopped
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ThreadStatus> for u8 {
|
||||
fn from(value: ThreadStatus) -> Self {
|
||||
value as u8
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user