pub trait ThreadFn {
// Required methods
fn spawn<F>(
&mut self,
param: Option<ThreadParam>,
callback: F,
) -> Result<Self>
where F: Fn(Box<dyn Thread>, Option<ThreadParam>) -> Result<ThreadParam> + Send + Sync + 'static,
Self: Sized;
fn spawn_simple<F>(&mut self, callback: F) -> Result<Self>
where F: Fn() + Send + Sync + 'static,
Self: Sized;
fn delete(&self);
fn suspend(&self);
fn resume(&self);
fn join(&self, retval: DoublePtr) -> Result<i32>;
fn get_metadata(&self) -> ThreadMetadata;
fn get_current() -> Self
where Self: Sized;
fn notify(&self, notification: ThreadNotification) -> Result<()>;
fn notify_from_isr(
&self,
notification: ThreadNotification,
higher_priority_task_woken: &mut BaseType,
) -> Result<()>;
fn wait_notification(
&self,
bits_to_clear_on_entry: u32,
bits_to_clear_on_exit: u32,
timeout_ticks: TickType,
) -> Result<u32>;
}Expand description
Core thread/task trait.
Provides methods for thread lifecycle management, synchronization, and communication through task notifications.
§Thread Creation
Threads are typically created with Thread::new() specifying name,
stack size, and priority, then started with spawn() or spawn_simple().
§Thread Safety
All methods are thread-safe. ISR-specific methods (suffixed with _from_isr)
should only be called from interrupt context.
§Resource Management
Threads should be properly deleted with delete() when no longer needed
to free stack memory and control structures.
§Examples
use osal_rs::os::{Thread, System};
use std::sync::Arc;
// Create and spawn a simple thread
let mut thread = Thread::new("worker", 2048, 5);
thread.spawn_simple(|| {
loop {
println!("Working...");
System::delay(1000);
}
}).unwrap();
// Create thread with parameter
let mut thread2 = Thread::new("counter", 1024, 5);
let counter = Arc::new(0u32);
thread2.spawn(Some(counter.clone()), |_thread, param| {
// Use param here
Ok(param.unwrap())
}).unwrap();Required Methods§
Sourcefn spawn<F>(&mut self, param: Option<ThreadParam>, callback: F) -> Result<Self>where
F: Fn(Box<dyn Thread>, Option<ThreadParam>) -> Result<ThreadParam> + Send + Sync + 'static,
Self: Sized,
fn spawn<F>(&mut self, param: Option<ThreadParam>, callback: F) -> Result<Self>where
F: Fn(Box<dyn Thread>, Option<ThreadParam>) -> Result<ThreadParam> + Send + Sync + 'static,
Self: Sized,
Spawns a thread with a callback function and optional parameter.
Creates and starts a new thread that executes the provided callback function. The callback receives a handle to itself and an optional parameter.
§Parameters
param- Optional type-erased parameter passed to the callbackcallback- Function to execute in the thread context
§Returns
Ok(Self)- Thread spawned successfullyErr(Error)- Failed to create or start thread
§Examples
use osal_rs::os::Thread;
use std::sync::Arc;
let mut thread = Thread::new("worker", 1024, 5);
let counter = Arc::new(100u32);
thread.spawn(Some(counter.clone()), |thread, param| {
if let Some(p) = param {
if let Some(count) = p.downcast_ref::<u32>() {
println!("Starting with count: {}", count);
}
}
Ok(Arc::new(200u32))
}).unwrap();Sourcefn spawn_simple<F>(&mut self, callback: F) -> Result<Self>
fn spawn_simple<F>(&mut self, callback: F) -> Result<Self>
Spawns a simple thread with a callback function (no parameters).
Creates and starts a new thread that executes the provided callback.
This is a simpler version of spawn() for threads that don’t need
parameters or self-reference.
§Parameters
callback- Function to execute in the thread context
§Returns
Ok(Self)- Thread spawned successfullyErr(Error)- Failed to create or start thread
§Examples
use osal_rs::os::{Thread, System};
let mut thread = Thread::new("blinker", 512, 3);
thread.spawn_simple(|| {
loop {
toggle_led();
System::delay(500);
}
}).unwrap();Sourcefn delete(&self)
fn delete(&self)
Deletes the thread and frees its resources.
Terminates the thread and releases its stack and control structures. After calling this, the thread handle becomes invalid.
§Safety
- The thread should not be holding any resources (mutexes, etc.)
- Other threads should not be waiting on this thread
- Cannot delete the currently running thread (use from another thread)
§Examples
use osal_rs::os::Thread;
let mut thread = Thread::new("temp", 512, 1);
thread.spawn_simple(|| {
// Do some work
}).unwrap();
// Later, from another thread
thread.delete();Sourcefn suspend(&self)
fn suspend(&self)
Suspends the thread.
Prevents the thread from executing until resume() is called.
The thread state is preserved and can be resumed later.
§Use Cases
- Temporarily pause a thread
- Debugging and development
- Dynamic task management
§Examples
use osal_rs::os::Thread;
let thread = Thread::current();
thread.suspend(); // Pauses this threadSourcefn join(&self, retval: DoublePtr) -> Result<i32>
fn join(&self, retval: DoublePtr) -> Result<i32>
Waits for the thread to complete and retrieves its return value.
Blocks the calling thread until this thread terminates. The thread’s return value is stored in the provided pointer.
§Parameters
retval- Pointer to store the thread’s return value
§Returns
Ok(exit_code)- Thread completed successfullyErr(Error)- Join operation failed
§Examples
use osal_rs::os::Thread;
let mut thread = Thread::new("worker", 1024, 1);
thread.spawn_simple(|| {
// Do work
}).unwrap();
let mut retval = core::ptr::null_mut();
thread.join(&mut retval).unwrap();Sourcefn get_metadata(&self) -> ThreadMetadata
fn get_metadata(&self) -> ThreadMetadata
Gets metadata about the thread.
Returns information such as thread name, priority, stack usage, and current state.
§Returns
ThreadMetadata structure containing thread information
§Examples
use osal_rs::os::Thread;
let thread = Thread::current();
let meta = thread.get_metadata();
println!("Thread: {} Priority: {}", meta.name, meta.priority);Sourcefn get_current() -> Selfwhere
Self: Sized,
fn get_current() -> Selfwhere
Self: Sized,
Gets a handle to the currently executing thread.
Returns a handle to the thread that is currently running. Useful for self-referential operations.
§Returns
Handle to the current thread
§Examples
use osal_rs::os::Thread;
let current = Thread::get_current();
let meta = current.get_metadata();
println!("Running in thread: {}", meta.name);Sourcefn notify(&self, notification: ThreadNotification) -> Result<()>
fn notify(&self, notification: ThreadNotification) -> Result<()>
Sends a notification to the thread.
Notifies the thread using the specified notification action. Task notifications are a lightweight signaling mechanism.
§Parameters
notification- The notification action to perform
§Returns
Ok(())- Notification sent successfullyErr(Error)- Failed to send notification
§Examples
use osal_rs::os::{Thread, ThreadNotification};
let worker = get_worker_thread();
// Signal an event
worker.notify(ThreadNotification::SetBits(0b0001)).unwrap();
// Send a value
worker.notify(ThreadNotification::SetValueWithOverwrite(42)).unwrap();Sourcefn notify_from_isr(
&self,
notification: ThreadNotification,
higher_priority_task_woken: &mut BaseType,
) -> Result<()>
fn notify_from_isr( &self, notification: ThreadNotification, higher_priority_task_woken: &mut BaseType, ) -> Result<()>
Sends a notification to the thread from ISR context.
ISR-safe version of notify(). Must only be called from interrupt context.
§Parameters
notification- The notification action to performhigher_priority_task_woken- Set to non-zero if a context switch should occur
§Returns
Ok(())- Notification sent successfullyErr(Error)- Failed to send notification
§Examples
use osal_rs::os::{Thread, ThreadNotification, System};
// In interrupt handler
fn isr_handler() {
let worker = get_worker_thread();
let mut task_woken = 0;
worker.notify_from_isr(
ThreadNotification::Increment,
&mut task_woken
).ok();
System::yield_from_isr(task_woken);
}Sourcefn wait_notification(
&self,
bits_to_clear_on_entry: u32,
bits_to_clear_on_exit: u32,
timeout_ticks: TickType,
) -> Result<u32>
fn wait_notification( &self, bits_to_clear_on_entry: u32, bits_to_clear_on_exit: u32, timeout_ticks: TickType, ) -> Result<u32>
Waits for a notification.
Blocks the calling thread until a notification is received or timeout occurs. Allows clearing specific bits on entry and/or exit.
§Parameters
bits_to_clear_on_entry- Bits to clear before waitingbits_to_clear_on_exit- Bits to clear after receiving notificationtimeout_ticks- Maximum ticks to wait (0 = no wait, MAX = wait forever)
§Returns
Ok(notification_value)- Notification received, returns the notification valueErr(Error::Timeout)- No notification received within timeoutErr(Error)- Other error occurred
§Note
This method does not use ToTick trait to maintain dynamic dispatch compatibility.
§Examples
use osal_rs::os::Thread;
let current = Thread::get_current();
// Wait for notification, clear all bits on exit
match current.wait_notification(0, 0xFFFFFFFF, 1000) {
Ok(value) => println!("Notified with value: {}", value),
Err(_) => println!("Timeout waiting for notification"),
}
// Wait for specific bits
let bits_of_interest = 0b0011;
match current.wait_notification(0, bits_of_interest, 5000) {
Ok(value) => {
if value & bits_of_interest != 0 {
println!("Received expected bits");
}
},
Err(_) => println!("Timeout"),
}