359

What is the best way to create and use a struct with only one instantiation in the system? Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of this and passing it around everywhere would add confusion, rather than relieve it.

The singleton needs to be as efficient as possible. It doesn't seem possible to store an arbitrary object on the static area, as it contains a Vec with a destructor. The second option is to store an (unsafe) pointer on the static area, pointing to a heap allocated singleton. What is the most convenient and safest way to do this, while keeping syntax terse?

4
  • 2
    Have you looked at how the existing Rust bindings for OpenGL handle this same problem?
    – Shepmaster
    Commented Jan 6, 2015 at 3:14
  • 37
    Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of this and passing it around everywhere would add confusion, rather than relieve it. => this is not the definition of necessary, it is maybe convenient (at first) but not necessary. Commented Jan 6, 2015 at 7:11
  • 3
    Yes you have a point. Although since OpenGL is a big state machine anyway, I am close to certain there will not be a clone of it anywhere, whose use would only result in OpenGL errors. Commented Jan 7, 2015 at 0:37
  • 9
    @MatthieuM. It is necessary for convenience.
    – Asker
    Commented Jan 8, 2023 at 13:07

9 Answers 9

480

Non-answer answer

Avoid global state in general. Instead, construct the object somewhere early (perhaps in main), then pass mutable references to that object into the places that need it. This will usually make your code easier to reason about and doesn't require as much bending over backwards.

Look hard at yourself in the mirror before deciding that you want global mutable variables. There are rare cases where it's useful, so that's why it's worth knowing how to do.

Still want to make one...?

Tips

In the following solutions:

  • If you remove the Mutex then you have a global singleton without any mutability.
  • You can also use a RwLock instead of a Mutex to allow multiple concurrent readers.

Using std::sync::LazyLock

LazyLock was stabilized as of Rust 1.80.0. It can be used to eliminate the inconvenience of OnceLock's helper function:

use std::sync::{LazyLock, Mutex};

static ARRAY: LazyLock<Mutex<Vec<u8>>> = LazyLock::new(|| Mutex::new(vec![]));

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", ARRAY.lock().unwrap().len());
}

Using std::sync::OnceLock

OnceLock was stabilized as of Rust 1.70.0. You can use it to get a dependency-free implementation:

use std::sync::{Mutex, OnceLock};

fn array() -> &'static Mutex<Vec<u8>> {
    static ARRAY: OnceLock<Mutex<Vec<u8>>> = OnceLock::new();
    ARRAY.get_or_init(|| Mutex::new(vec![]))
}

fn do_a_call() {
    array().lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", array().lock().unwrap().len());
}

Using lazy-static

The lazy-static crate can take away some of the drudgery of manually creating a singleton. Here is a global mutable vector:

use lazy_static::lazy_static; // 1.4.0
use std::sync::Mutex;

lazy_static! {
    static ref ARRAY: Mutex<Vec<u8>> = Mutex::new(vec![]);
}

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", ARRAY.lock().unwrap().len());
}

Using once_cell

The once_cell crate can take away some of the drudgery of manually creating a singleton. Here is a global mutable vector:

use once_cell::sync::Lazy; // 1.3.1
use std::sync::Mutex;

static ARRAY: Lazy<Mutex<Vec<u8>>> = Lazy::new(|| Mutex::new(vec![]));

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", ARRAY.lock().unwrap().len());
}

A special case: atomics

If you only need to track an integer value, you can directly use an atomic:

use std::sync::atomic::{AtomicUsize, Ordering};

static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);

fn do_a_call() {
    CALL_COUNT.fetch_add(1, Ordering::SeqCst);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", CALL_COUNT.load(Ordering::SeqCst));
}

Manual, dependency-free implementation

There are several existing implementation of statics, such as the Rust 1.0 implementation of stdin. This is the same idea adapted to modern Rust, such as the use of MaybeUninit to avoid allocations and unnecessary indirection. You should also look at the modern implementation of io::Lazy. I've commented inline with what each line does.

use std::sync::{Mutex, Once};
use std::time::Duration;
use std::{mem::MaybeUninit, thread};

struct SingletonReader {
    // Since we will be used in many threads, we need to protect
    // concurrent access
    inner: Mutex<u8>,
}

fn singleton() -> &'static SingletonReader {
    // Create an uninitialized static
    static mut SINGLETON: MaybeUninit<SingletonReader> = MaybeUninit::uninit();
    static ONCE: Once = Once::new();

    unsafe {
        ONCE.call_once(|| {
            // Make it
            let singleton = SingletonReader {
                inner: Mutex::new(0),
            };
            // Store it to the static var, i.e. initialize it
            SINGLETON.write(singleton);
        });

        // Now we give out a shared reference to the data, which is safe to use
        // concurrently.
        SINGLETON.assume_init_ref()
    }
}

fn main() {
    // Let's use the singleton in a few threads
    let threads: Vec<_> = (0..10)
        .map(|i| {
            thread::spawn(move || {
                thread::sleep(Duration::from_millis(i * 10));
                let s = singleton();
                let mut data = s.inner.lock().unwrap();
                *data = i as u8;
            })
        })
        .collect();

    // And let's check the singleton every so often
    for _ in 0u8..20 {
        thread::sleep(Duration::from_millis(5));

        let s = singleton();
        let data = s.inner.lock().unwrap();
        println!("It is: {}", *data);
    }

    for thread in threads.into_iter() {
        thread.join().unwrap();
    }
}

This prints out:

It is: 0
It is: 1
It is: 1
It is: 2
It is: 2
It is: 3
It is: 3
It is: 4
It is: 4
It is: 5
It is: 5
It is: 6
It is: 6
It is: 7
It is: 7
It is: 8
It is: 8
It is: 9
It is: 9
It is: 9

This code compiles with Rust 1.55.0.

All of this work is what lazy-static or once_cell do for you.

The meaning of "global"

Please note that you can still use normal Rust scoping and module-level privacy to control access to a static or lazy_static variable. This means that you can declare it in a module or even inside of a function and it won't be accessible outside of that module / function. This is good for controlling access:

use lazy_static::lazy_static; // 1.2.0

fn only_here() {
    lazy_static! {
        static ref NAME: String = String::from("hello, world!");
    }
    
    println!("{}", &*NAME);
}

fn not_here() {
    println!("{}", &*NAME);
}
error[E0425]: cannot find value `NAME` in this scope
  --> src/lib.rs:12:22
   |
12 |     println!("{}", &*NAME);
   |                      ^^^^ not found in this scope

However, the variable is still global in that there's one instance of it that exists across the entire program.

24
  • 117
    After a lot of thought I'm convinced not to use the Singleton, and instead use no global variables at all and pass everything around. Makes the code more self-documenting since it is clear what functions access the renderer. If I want to change back to singleton, it will be easier to do that than the other way around. Commented Jan 8, 2015 at 0:48
  • 7
    Thanks for the answer, it helped a lot. I just thought I'd let here a comment to describe what I see as a valid use case for lazy_static!. I am using it to interface to a C application that allows loading/unloading modules (shared objects) and the rust code is one of these modules. I don't see much option than using a global on load because I have no control over main() at all and how the core application interfaces with my module. I basically needed a vector of things that can be added on runtime after my mod is loaded. Commented Aug 6, 2016 at 17:11
  • 3
    Yeah passing around context would work, but this is a large application we don't really have much control over and changing the interface to modules would imply updating hundreds of third party modules or creating a new module API, both changes involve far more work than just writing a plugin module using lazy-static. Commented Aug 8, 2016 at 14:56
  • 5
    Not a good answer. Avoid global state in general but global state is a thing and need representation. And the code for external static is flawed and will not compile on rustc 1.24.1
    – Worik
    Commented May 21, 2018 at 21:47
  • 7
    @Worik would you care to explain why? I discourage people from doing something that is a poor idea in most languages (even the OP agreed that a global was a bad choice for their application). That's what in general means. I then show two solutions for how to do it anyway. I just tested the lazy_static example in Rust 1.24.1 and it works exactly. There's no external static anywhere here. Perhaps you need to check things on your end to make sure you've understood the answer fully.
    – Shepmaster
    Commented May 21, 2018 at 21:50
33

Starting with Rust 1.63, it can be easier to work with global mutable singletons, although it's still preferable to avoid global variables in most cases.

Now that Mutex::new is const, you can use global static Mutex locks without needing lazy initialization:

use std::sync::Mutex;

static GLOBAL_DATA: Mutex<Vec<i32>> = Mutex::new(Vec::new());

fn main() {
    GLOBAL_DATA.lock().unwrap().push(42);
    println!("{:?}", GLOBAL_DATA.lock().unwrap());
}

Note that this also depends on the fact that Vec::new is const. If you need to use non-const functions to set up your singleton, you could wrap your data in an Option, and initially set it to None. This lets you use data structures like Hashset which currently cannot be used in a const context:

use std::sync::Mutex;
use std::collections::HashSet;

static GLOBAL_DATA: Mutex<Option<HashSet<i32>>> = Mutex::new(None);

fn main() {
    *GLOBAL_DATA.lock().unwrap() = Some(HashSet::from([42]));
    println!("V2: {:?}", GLOBAL_DATA.lock().unwrap());
}

Alternatively, you could use an RwLock, instead of a Mutex, since RwLock::new is also const as of Rust 1.63. This would make it possible to read the data from multiple threads simultaneously.

If you need to initialize with non-const functions and you'd prefer not to use an Option, you could use a crate like once_cell or lazy-static for lazy initialization as explained in Shepmaster's answer.

0
6

From What Not To Do In Rust

To recap: instead of using interior mutability where an object changes its internal state, consider using a pattern where you promote new state to be current and current consumers of the old state will continue to hold on to it by putting an Arc into an RwLock.

use std::sync::{Arc, RwLock};

#[derive(Default)]
struct Config {
    pub debug_mode: bool,
}

impl Config {
    pub fn current() -> Arc<Config> {
        CURRENT_CONFIG.with(|c| c.read().unwrap().clone())
    }
    pub fn make_current(self) {
        CURRENT_CONFIG.with(|c| *c.write().unwrap() = Arc::new(self))
    }
}

thread_local! {
    static CURRENT_CONFIG: RwLock<Arc<Config>> = RwLock::new(Default::default());
}

fn main() {
    Config { debug_mode: true }.make_current();
    if Config::current().debug_mode {
        // do something
    }
}
2
  • 7
    Hi, please see this question as I'm not sure the thread_local is correct, as it will create multiple instances of the Arc<Config> (one per running thread).
    – thargy
    Commented Aug 16, 2021 at 17:37
  • 1
    Also, isn't it more or less pointless to use thread-safe data structures like RwLock and Arc inside a thread_local! storage that cannot pass thread boundaries by design? Shouldn't the non-thread-safe versions RefCell and Rc be sufficient here?
    – bluenote10
    Commented Sep 15, 2023 at 9:26
3

If you are on nightly, you can use LazyLock.

It more or less does what the crates once_cell and lazy_sync do. Those two crates are very common, so there's a good chance they might already by in your Cargo.lock dependency tree. But if you prefer to be a bit more "adventurous" and go with LazyLock, be prepered that it (as everything in nightly) might be a subject to change before it gets to stable.

(Note: Up until recently std::sync::LazyLock used to be named std::lazy::SyncLazy but was recently renamed.)

2

Use SpinLock for global access.

#[derive(Default)]
struct ThreadRegistry {
    pub enabled_for_new_threads: bool,
    threads: Option<HashMap<u32, *const Tls>>,
}

impl ThreadRegistry {
    fn threads(&mut self) -> &mut HashMap<u32, *const Tls> {
        self.threads.get_or_insert_with(HashMap::new)
    }
}

static THREAD_REGISTRY: SpinLock<ThreadRegistry> = SpinLock::new(Default::default());

fn func_1() {
    let thread_registry = THREAD_REGISTRY.lock();  // Immutable access
    if thread_registry.enabled_for_new_threads {
    }
}

fn func_2() {
    let mut thread_registry = THREAD_REGISTRY.lock();  // Mutable access
    thread_registry.threads().insert(
        // ...
    );
}

If you want mutable state(NOT Singleton), see What Not to Do in Rust for more descriptions.

Hope it's helpful.

1

A bit late to the party, but here's how I worked around this issue (rust 1.66-nightly):

#![feature(const_size_of_val)]
#![feature(const_ptr_write)]

static mut GLOBAL_LAZY_MUT: StructThatIsNotSyncNorSend = unsafe {
    // Copied from MaybeUninit::zeroed() with minor modifications, see below
    let mut u = MaybeUninit::uninit();

    let bytes = mem::size_of_val(&u);
    write_bytes(u.as_ptr() as *const u8 as *mut u8, 0xA5, bytes); //Trick the compiler check that verifies pointers and references are not null.

    u.assume_init()
};

(...)

fn main() {
    unsafe {
        let mut v = StructThatIsNotSyncNorSend::new();
        mem::swap(&mut GLOBAL_LAZY_MUT, &mut v);
        mem::forget(v);
    }
  
}

Beware that this code is unbelievably unsafe, and can easily end up being UB if not handled correctly.

You now have a !Send !Sync value as a global static, without the protection of a Mutex. If you access it from multiple threads, even if just for reading, it's UB. If you don't initialize it the way shown, it's UB, because it calls Drop on an actually unitialized value.

You just convinced the rust compiler that something that is UB is not UB. You just convinced that putting a !Sync and !Send in a global static is fine.

If unsure, don't use this snippet.

7
  • 1
    Why is this not UB? You are creating an uninitialized value, which, AFAIK, is instantaneous UB even if you don't read it before properly initializing it. Also, you have an unsafe block within an unsafe block (maybe to point out it really unsafe?)
    – jthulhu
    Commented Feb 3, 2023 at 9:37
  • The nested unsafe is not necessary, that is a mistake. The code is not UB because the value is overwritten before it is read (the initialization needs to be in main, before any race conditions could happen). What you may be referring to (UB even it it's not read) happens if the value is overwritten, and the rust compiler tries to Drop the old (unitited) value. Since it's mem::swap-ped and mem::forget-ted here, that doesn't happen. Commented Feb 3, 2023 at 19:47
  • 1
    That may seem intuitively correct, and yet, even having an unitialized variable, even if you never access it, is UB, I think. See the doc, in particular the example with bool which seems to match your snippet.
    – jthulhu
    Commented Feb 3, 2023 at 22:10
  • I feel like you're not correct, but I'm not entirely sure either. These two snippets in the doc seem to contradict: For example, a 1-initialized Vec<T> is considered initialized (under the current implementation; this does not constitute a stable guarantee) because the only requirement the compiler knows about it is that the data pointer must be non-null. Creating such a Vec<T> does not cause immediate undefined behavior, but will cause undefined behavior with most safe operations (including dropping it)., meaning that initializing the memory to 0xA5 will not cause immediate UB, however Commented Feb 3, 2023 at 22:18
  • 1
0

Besides the 3rd-party crates, the alternative is to wrap your custom type (e.g. struct) within std::sync::Mutex.

  • The Mutex protects the instance of the custom type in concurrent accesses of multi-threading usage scenario
  • The caller successfully getting the lock from Mutex can modify the content of the custom type.

Here's the code example :

use std::sync::Mutex;

#[derive(Debug)]
struct Rectangle {
    width :u16,
    height:u16,
}

static GLOBAL_COUNTER_2: Mutex<Rectangle> = 
    Mutex::new(
        Rectangle{width:100u16, height:125u16}
    );

fn  global_var_demo()
{
    if let Ok(mut value) = GLOBAL_COUNTER_2.lock() {
        value.width += 7;
        value.height = value.height >> 1;
    }
    if let Ok(value) = GLOBAL_COUNTER_2.lock() {
        // request the reference without moving the ownership
        assert_eq!(value.width, 107u16);
        println!("new value in GLOBAL_COUNTER_2: {:?}", value);
    }
}
2
  • Mutex already guarantees exclusive access and allows you to mutate it's interior, the Cell is unnecessary which is demonstrated by your use of Cell::get_mut(&mut self) which already takes a mutable reference.
    – cafce25
    Commented Oct 9, 2023 at 6:16
  • Thanks, I found that mut value assigned by the mutex.lock() should be sufficient to modify the internal instance. It seems that somebody downvoted my answer just because it wasn't precise enough. :)
    – T.H.
    Commented Oct 9, 2023 at 10:31
-3

My limited solution is to define a struct instead of a global mutable one. To use that struct, external code needs to call init() but we disallow calling init() more than once by using an AtomicBoolean (for multithreading usage).

static INITIATED: AtomicBool = AtomicBool::new(false);

struct Singleton {
  ...
}

impl Singleton {
  pub fn init() -> Self {
    if INITIATED.load(Ordering::Relaxed) {
      panic!("Cannot initiate more than once")
    } else {
      INITIATED.store(true, Ordering::Relaxed);

      Singleton {
        ...
      }
    }
  }
}

fn main() {
  let singleton = Singleton::init();
  
  // panic here
  // let another_one = Singleton::init();
  ...
}
-3

I have been using C++for a considerable amount of time, and I am accustomed to using singleton mode. I implement this in Rust, but of course, it is not thread safe. If you need thread safety, you can use mutexes

in c++:

class Manager
{
public:
    static Manager* instance();
    static void destroy();
}

in rust:

use std::{mem};

struct Manager {
    count: i32
}

static mut MANAGER_INSTANCE: Option<&'static mut Manager> = Option::None;

impl Drop for Manager {
    fn drop(&mut self) {
        println!("Dropping me!");
    }
}

impl Manager {
    pub fn instance() -> &'static mut Manager {
        unsafe {
            match MANAGER_INSTANCE {
                Option::Some(ref mut manager) => *manager,
                Option::None => {
                    println!("new instance!");
                    let manager_box = Box::new(Manager {count: 0});
                    let manager_raw = Box::into_raw(manager_box);
                    MANAGER_INSTANCE = Some(&mut *manager_raw);
                    &mut *manager_raw
                }
            }
        }
    }

    pub fn destroy() {
        unsafe {
            if let Some(raw) = mem::replace(&mut MANAGER_INSTANCE, None) {
                Box::from_raw(raw);
            }
        }
    }

    pub fn call_me(&mut self) {
        self.count += 1;
        println!("count: {}", self.count);
    }
}



#[tokio::main]
pub async fn main() {
    Manager::instance().call_me();
    Manager::instance().call_me();
    Manager::instance().call_me();
    Manager::destroy();
    Manager::instance().call_me();
    Manager::instance().call_me();
    Manager::instance().call_me();
    Manager::destroy();

    tokio::spawn(async {
        Manager::destroy();
        Manager::instance().call_me();
        Manager::destroy();
    }).await;
}
1
  • WHY not just use OnceCell<Mutex> or thread_local!(RefCell)? Your code is both unsafe and unsound. Commented Dec 1, 2023 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.