rust icon indicating copy to clipboard operation
rust copied to clipboard

Thread name is not set

Open elwerene opened this issue 3 years ago • 3 comments

I tried this code:

thread::Builder::new().name("thread1".to_string()).spawn(move || {
    println!("Hello, world!");
});

I expected to see this happen: The thread/freertos task gets names thread1

Instead, this happened: The thread/freertos task gets names pthread

My guess of a reason

There's not set_name implemented for espidf:

https://github.com/esp-rs/rust/blob/esp-1.64.0.0/library/std/src/sys/unix/thread.rs#L205

So the pthread name is not set and it defaults to pthread:

https://github.com/espressif/esp-idf/blob/master/components/pthread/pthread.c#L237

elwerene avatar Sep 27 '22 07:09 elwerene

I dug a bit more into it and I found that the thread is created in Thread::new and the name is afterwards set in Thread::set_name. But in the espidf libc, the name must be set prior to creating a new thread/task.

This works:

let thread_name = CString::new("thread1").unwrap();
let mut esp_thread_cfg = esp_idf_sys::esp_pthread_get_default_config();
esp_thread_cfg.thread_name = thread_name.as_ptr();
esp_idf_sys::esp_pthread_set_cfg(&esp_thread_cfg);

thread::Builder::new().name("thread1".to_string()).spawn(move || {
    println!("Hello, world!");
});

elwerene avatar Sep 28 '22 13:09 elwerene

Maybe there's some function to set a task name in freertos after it was created?

elwerene avatar Sep 28 '22 13:09 elwerene

I made this little helper function which I'm using in own of my projects until this issue is resolved:

pub fn spawn<F, T>(
    name: &'static str,
    stack_size: usize,
    f: F,
) -> std::io::Result<std::thread::JoinHandle<T>>
where
    F: FnOnce() -> T,
    F: Send + 'static,
    T: Send + 'static,
{
    let thread_name = std::ffi::CString::new(name).unwrap();
    let mut esp_thread_cfg = unsafe { esp_idf_sys::esp_pthread_get_default_config() };
    esp_thread_cfg.thread_name = thread_name.into_raw();
    unsafe { esp_idf_sys::esp_pthread_set_cfg(&esp_thread_cfg) };
    let thread_builder = std::thread::Builder::new().stack_size(stack_size);
    thread_builder.spawn(f)
}

elwerene avatar Sep 28 '22 13:09 elwerene