0

I need to create some global mutable variables, using lazy_static! with some types works, but with some other types it doesn't. The mutex is to change value.

This works:

lazy_static! {
    static ref foo: Mutex<String>: Mutex::new("".to_string());
}

This doesn't (the Function is js_sys::Function)

lazy_static! {
    static ref bar: Mutex<Option<Function>> = Mutex::new(None);
}

The error is: *mut u8 is not safe to send between threads

My current work-around is using thread_local! for global mutable vars, but I need threads. How to use lazy_static with all types?

Dee
  • 7,455
  • 6
  • 36
  • 70
  • 1
    The issue is hidden in the error message, `Function` has an internal `*mut u8` pointer and raw pointers are neither `Send` nor `Sync`. `Send` is a requirement of `lazy_static`, thus you get the error message. If it's safe to ensure unique access through `Arc>` you could implement a thin wrapper and manually implement `Send` + `Sync` for it. – sebpuetz Jun 11 '21 at 11:35
  • 1
    you can use `Pin` – Sahandevs Jun 11 '21 at 11:39

0 Answers0