rust
rust copied to clipboard
Thread name is not set
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
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!");
});
Maybe there's some function to set a task name in freertos after it was created?
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)
}