Skip to main content

Thread

Struct Thread 

Source
pub struct Thread { /* private fields */ }
Expand description

A FreeRTOS task/thread wrapper.

Provides a safe Rust interface for creating and managing FreeRTOS tasks. Threads can be created with closures or function pointers and support various synchronization primitives.

§Examples

§Creating a simple thread

use osal_rs::os::{Thread, ThreadPriority};
use core::time::Duration;
 
let thread = Thread::new(
    "worker",
    2048,  // stack size in words
    ThreadPriority::Normal,
    || {
        loop {
            println!("Working...");
            Duration::from_secs(1).sleep();
        }
    }
).unwrap();
 
thread.start().unwrap();

§Using thread notifications

use osal_rs::os::{Thread, ThreadNotification};
use core::time::Duration;
 
let thread = Thread::new("notified", 2048, 5, || {
    loop {
        if let Some(value) = Thread::current().wait_notification(Duration::from_secs(1)) {
            println!("Received notification: {}", value);
        }
    }
}).unwrap();
 
thread.start().unwrap();
thread.notify(42).unwrap();  // Send notification

Implementations§

Source§

impl Thread

Source

pub fn new(name: &str, stack_depth: StackType, priority: UBaseType) -> Self

Creates a new uninitialized thread.

The thread must be started with spawn() or spawn_simple().

§Examples
use osal_rs::os::{Thread, ThreadFn};
 
let thread = Thread::new("worker", 4096, 5);
Source

pub fn new_with_handle( handle: ThreadHandle, name: &str, stack_depth: StackType, priority: UBaseType, ) -> Result<Self>

Creates a thread from an existing task handle.

§Returns
  • Err(Error::NullPtr) if handle is null
Source

pub fn new_with_to_priority( name: &str, stack_depth: StackType, priority: impl ToPriority, ) -> Self

Creates a new thread with a priority that implements ToPriority.

This is a convenience constructor that allows using various priority types.

§Parameters
  • name - Thread name for debugging
  • stack_depth - Stack size in words (not bytes)
  • priority - Thread priority (any type implementing ToPriority)
§Examples
use osal_rs::os::Thread;
 
let thread = Thread::new_with_to_priority("worker", 2048, 5);
Source

pub fn new_with_handle_and_to_priority( handle: ThreadHandle, name: &str, stack_depth: StackType, priority: impl ToPriority, ) -> Result<Self>

Creates a thread from an existing FreeRTOS task handle.

§Parameters
  • handle - Valid FreeRTOS task handle
  • name - Thread name
  • stack_depth - Stack size
  • priority - Thread priority
§Returns
  • Err(Error::NullPtr) if handle is null
§Examples
use osal_rs::os::Thread;
 
// Get current task handle from FreeRTOS
let handle = get_task_handle();
let thread = Thread::new_with_handle_and_to_priority(handle, "existing", 2048, 5).unwrap();
Source

pub fn get_metadata_from_handle(handle: ThreadHandle) -> ThreadMetadata

Retrieves metadata for a thread from its handle.

§Parameters
  • handle - FreeRTOS task handle
§Returns

Thread metadata including state, priority, stack usage, etc.

§Examples
use osal_rs::os::Thread;
 
let handle = get_some_task_handle();
let metadata = Thread::get_metadata_from_handle(handle);
println!("Thread '{}' state: {:?}", metadata.name, metadata.state);
Source

pub fn get_metadata(thread: &Thread) -> ThreadMetadata

Retrieves metadata for a thread object.

§Parameters
  • thread - Thread reference
§Returns

Thread metadata or default if handle is null

§Examples
use osal_rs::os::Thread;
 
let thread = Thread::new("worker", 2048, 5);
let metadata = Thread::get_metadata(&thread);
println!("Stack high water mark: {}", metadata.stack_high_water_mark);
Source

pub fn wait_notification_with_to_tick( &self, bits_to_clear_on_entry: u32, bits_to_clear_on_exit: u32, timeout_ticks: impl ToTick, ) -> Result<u32>

Waits for a thread notification with a timeout that implements ToTick.

Convenience method that accepts Duration or other tick-convertible types.

§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 time to wait (convertible to ticks)
§Returns
  • Ok(u32) - Notification value received
  • Err(Error::NullPtr) - Thread handle is null
  • Err(Error::Timeout) - No notification received within timeout
§Examples
use osal_rs::os::{Thread, ThreadFn};
use core::time::Duration;
 
let thread = Thread::current();
match thread.wait_notification_with_to_tick(0, 0xFF, Duration::from_secs(1)) {
    Ok(value) => println!("Received: {}", value),
    Err(_) => println!("Timeout"),
}

Trait Implementations§

Source§

impl Clone for Thread

Source§

fn clone(&self) -> Thread

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Thread

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Thread

Source§

type Target = *const c_void

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Display for Thread

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Thread for Thread

Source§

fn spawn<F>(&mut self, param: Option<ThreadParam>, callback: F) -> Result<Self>
where F: Fn(Box<dyn ThreadFn>, Option<ThreadParam>) -> Result<ThreadParam> + Send + Sync + 'static,

Spawns a new thread with a callback.

§Important

The callback must be 'static, which means it cannot borrow local variables. Use move in the closure to transfer ownership of any captured values:

let data = Arc::new(Mutex::new(0));
let thread = Thread::new("my_thread", 4096, 3, move |_thread, _param| {
    // Use 'move' to capture 'data' by value
    let mut guard = data.lock().unwrap();
    *guard += 1;
    Ok(Arc::new(()))
});
``
Source§

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

Spawns a new thread with a simple closure, similar to std::thread::spawn. This is the recommended way to create threads for most use cases.

§Example
let counter = Arc::new(Mutex::new(0));
let counter_clone = Arc::clone(&counter);
 
let handle = Thread::spawn_simple("worker", 4096, 3, move || {
    let mut num = counter_clone.lock().unwrap();
    *num += 1;
}).unwrap();
 
handle.join(core::ptr::null_mut());
Source§

fn delete(&self)

Deletes the thread and frees its resources.

§Safety

After calling this, the thread handle becomes invalid.

§Examples
use osal_rs::os::{Thread, ThreadFn};
 
let thread = Thread::new("temp", 2048, 5);
thread.delete();
Source§

fn suspend(&self)

Suspends the thread execution.

The thread remains suspended until resume() is called.

§Examples
use osal_rs::os::{Thread, ThreadFn};
use core::time::Duration;
 
let thread = get_some_thread();
thread.suspend();
Duration::from_secs(1).sleep();
thread.resume();
Source§

fn resume(&self)

Resumes a previously suspended thread.

§Examples
thread.resume();
Source§

fn join(&self, _retval: DoublePtr) -> Result<i32>

Waits for the thread to complete (currently deletes the thread).

§Returns

Always returns Ok(0)

Source§

fn get_metadata(&self) -> ThreadMetadata

Retrieves this thread’s metadata.

§Examples
use osal_rs::os::{Thread, ThreadFn};
 
let thread = Thread::current();
let meta = thread.get_metadata();
println!("Running thread: {}", meta.name);
Source§

fn get_current() -> Self

Returns a Thread object representing the currently executing thread.

§Examples
use osal_rs::os::{Thread, ThreadFn};
 
let current = Thread::get_current();
println!("Current thread: {}", current.get_metadata().name);
Source§

fn notify(&self, notification: ThreadNotification) -> Result<()>

Sends a notification to this thread.

§Parameters
  • notification - Type of notification action to perform
§Returns
  • Ok(()) - Notification sent successfully
  • Err(Error::NullPtr) - Thread handle is null
  • Err(Error::QueueFull) - Notification failed
§Examples
use osal_rs::os::{Thread, ThreadFn, ThreadNotification};
 
let thread = get_worker_thread();
thread.notify(ThreadNotification::SetValueWithOverwrite(42)).unwrap();
Source§

fn notify_from_isr( &self, notification: ThreadNotification, higher_priority_task_woken: &mut BaseType, ) -> Result<()>

Sends a notification to this thread from an ISR.

§Parameters
  • notification - Type of notification action
  • higher_priority_task_woken - Set to pdTRUE if a higher priority task was woken
§Returns
  • Ok(()) - Notification sent successfully
  • Err(Error::NullPtr) - Thread handle is null
  • Err(Error::QueueFull) - Notification failed
§Examples
// In ISR context:
let mut woken = pdFALSE;
thread.notify_from_isr(ThreadNotification::Increment, &mut woken).ok();
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 thread notification.

§Parameters
  • bits_to_clear_on_entry - Bits to clear in notification value before waiting
  • bits_to_clear_on_exit - Bits to clear after receiving notification
  • timeout_ticks - Maximum ticks to wait
§Returns
  • Ok(u32) - Notification value received
  • Err(Error::NullPtr) - Thread handle is null
  • Err(Error::Timeout) - No notification within timeout
§Examples
use osal_rs::os::{Thread, ThreadFn};
 
let thread = Thread::current();
match thread.wait_notification(0, 0xFFFFFFFF, 1000) {
    Ok(value) => println!("Received notification: {}", value),
    Err(_) => println!("Timeout waiting for notification"),
}
Source§

impl Send for Thread

Source§

impl Sync for Thread

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.