Add ThreadExt and clean up PosixThreadExt

This commit is contained in:
Ruihan Li
2024-11-10 17:15:08 +08:00
committed by Tate, Hongliang Tian
parent a4a8807a20
commit 9233d1cdbb
13 changed files with 46 additions and 57 deletions

View File

@ -65,10 +65,7 @@ impl Thread {
/// This function returns `None` if the current task is not associated with
/// a thread, or if called within the bootstrap context.
pub fn current() -> Option<Arc<Self>> {
Task::current()?
.data()
.downcast_ref::<Arc<Thread>>()
.cloned()
Task::current()?.as_thread().cloned()
}
/// Returns the task associated with this thread.
@ -76,15 +73,6 @@ impl Thread {
self.task.upgrade().unwrap()
}
/// Gets the Thread from task's data.
///
/// # Panics
///
/// This method panics if the task is not a thread.
pub fn borrow_from_task(task: &Task) -> &Arc<Self> {
task.data().downcast_ref::<Arc<Thread>>().unwrap()
}
/// Runs this thread at once.
pub fn run(&self) {
self.status.store(ThreadStatus::Running, Ordering::Release);
@ -173,3 +161,15 @@ impl Thread {
&*self.data
}
}
/// An extension trait for [`Thread`]-like types.
pub trait ThreadExt {
/// Returns the associated [`Thread`].
fn as_thread(&self) -> Option<&Arc<Thread>>;
}
impl ThreadExt for Task {
fn as_thread(&self) -> Option<&Arc<Thread>> {
self.data().downcast_ref::<Arc<Thread>>()
}
}