Skip to main content

ThreadFn

Trait ThreadFn 

Source
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§

Source

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 callback
  • callback - Function to execute in the thread context
§Returns
  • Ok(Self) - Thread spawned successfully
  • Err(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();
Source

fn spawn_simple<F>(&mut self, callback: F) -> Result<Self>
where F: Fn() + Send + Sync + 'static, Self: Sized,

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 successfully
  • Err(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();
Source

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();
Source

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 thread
Source

fn resume(&self)

Resumes a suspended thread.

Resumes execution of a thread that was previously suspended with suspend(). If the thread was not suspended, this has no effect.

§Examples
// Thread 1
worker_thread.suspend();

// Thread 2
worker_thread.resume();  // Resume Thread 1
Source

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 successfully
  • Err(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();
Source

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);
Source

fn get_current() -> Self
where 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);
Source

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 successfully
  • Err(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();
Source

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 perform
  • higher_priority_task_woken - Set to non-zero if a context switch should occur
§Returns
  • Ok(()) - Notification sent successfully
  • Err(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);
}
Source

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 waiting
  • bits_to_clear_on_exit - Bits to clear after receiving notification
  • timeout_ticks - Maximum ticks to wait (0 = no wait, MAX = wait forever)
§Returns
  • Ok(notification_value) - Notification received, returns the notification value
  • Err(Error::Timeout) - No notification received within timeout
  • Err(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"),
}

Implementors§