Raw pointer and send / LazyLock

⚓ Rust    📅 2026-02-19    👤 surdeus    👁️ 6      

surdeus

Hello,

Just as a "warning" I'm not really sure whether I misunderstand the way I should use glib or whether it is a pointer / rust problem. But if I post here I'm rather sure it comes from me and it related to a rust problem otherwise I sincerely apologize in advance for the caused disturbance to an unrelated problem to rust.

I also want to add the fact that when developing this piece of code I had errors indicating that raw pointers weren't Send.

So here is my code:

static MAIN_LOOP: LazyLock<Arc<Mutex<Arc<glib_sys::glib::GMainLoop>>>> = LazyLock::<
    Arc<Mutex<Arc<glib_sys::glib::GMainLoop>>>,
>::new(|| {
    let context_ptr = unsafe { glib_sys::glib::g_main_context_default() };

    let main_loop = unsafe {
        glib_sys::glib::g_main_loop_new(
            context_ptr,
            std::ffi::c_int::try_from(glib_sys::glib::FALSE).unwrap(),
        )
    };

    Arc::<Mutex<Arc<glib_sys::glib::GMainLoop>>>::new(Mutex::<Arc<glib_sys::glib::GMainLoop>>::new(
        unsafe { Arc::<glib_sys::glib::GMainLoop>::from_raw(main_loop) },
    ))
});

/// run the main loop of the default context
///
/// # Panics
/// The main loop is then unable to run.
pub fn run_main_context_loop() {
    let main_loop = &mut MAIN_LOOP.lock().unwrap();
    let arc_main_loop = Arc::get_mut(main_loop).unwrap();
    if unsafe { glib_sys::glib::g_main_loop_is_running(arc_main_loop) }
        == i32::try_from(glib_sys::glib::FALSE).unwrap()
    {
        unsafe { glib_sys::glib::g_main_loop_run(arc_main_loop) }
    }
}

the function run_main_context_loop is run in a thread:

std::thread::spawn(move || {
     run_main_context_loop();
});

Unfortunately the glib thread crashes. I analyzed the stack and seems to come from this line:

pub fn run_main_context_loop() {
    ...
    // here it crashes
    let arc_main_loop = Arc::get_mut(main_loop).unwrap();
    ...
}

Thank you very much in advance for any help

2 posts - 2 participants

Read full topic

🏷️ Rust_feed