Initialize Mutex in global static object

Hi,

This is for testing and practice. I’ve global struct which doesn’t need thread safe access to the main object since individual fields are using Mutex. Following is example code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=90dce2819d49555abe2a334e5963b4da

Problem is:

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
  --> src/main.rs:21:8
   |
21 |     w: Mutex::new(100),
   |        ^^^^^^^^^^^^^^^

Is there a way to initialize mutex for the field? Unsafe code solution is acceptable.

Thanks in advance

lazy_static is the most used;

use lazy_static::lazy_static;
lazy_static!{
    static ref IMTHREADSAFE: ThreadSafeStruct = ThreadSafeStruct{
        w: Mutex::new(100),
    };
}

If your inner fields are const generated could try spin

Thanks for the reply. Any solution without using 3rd party libraries/crates?

lazy_static is the de-facto standard way for doing this. You could try and re-implement lazy static, but I don’t recommend it.

Thanks for the reply. I tried lazy_static, but it needs mutex on the main object to make it updateable which is not needed.

lazy_static is a very small and simple crate and there’s little reason not to use it. Here’s a post I wrote on a similar thread where I explain pretty much everything that it does.

I tried lazy_static, but it needs mutex on the main object to make it updateable which is not needed.

That’s because you defined update to take &mut self. Threadsafe APIs always take &self.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d46c4042b5a6daef675415ee04e5c8b9

&mut in rust doesn’t really mean “mutable” so much as it means “unique.” It means nothing else is pointing to the same data. That’s obviously impossible to guarantee for anything shared between threads, which is why & is used.

4 Likes

Thanks :+1:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.