Skip to content

[ch04/global-vars/src/main.rs] -- Redundant Use of Arc<Mutex<>> in thread_local! #23

@DannyCeb

Description

@DannyCeb

I've identified an inefficient pattern in the code where Arc<Mutex<Option<Vec>>> is used inside a thread_local! macro. This combination is redundant and represents an unnecessary use of atomic operations.

thread_local! {
    static POPULAR_BABY_NAMES_2021: Arc<Mutex<Option<Vec<String>>>> =
        Arc::new(Mutex::new(None));
}

I recommend changing to Rc<RefCell<Vec>> like the following example

use std::cell::RefCell;
use std::rc::Rc;

thread_local! {
    static POPULAR_BABY_NAMES_2021: Rc<RefCell<Vec<String>>> =
        Rc::new(RefCell::new(vec![]));
}

fn main() {
    let rc: Rc<RefCell<Vec<String>>> = POPULAR_BABY_NAMES_2021.with(|rc: &Rc<RefCell<Vec<String>>>| rc.clone());
    let mut inner: std::cell::RefMut<'_, Vec<String>> = rc.borrow_mut();
    inner.extend(vec![
        String::from("Olivia"),
        String::from("Liam"),
        String::from("Emma"),
        String::from("Noah"),
    ]);

    println!("popular baby names of 2021: {:?}", inner);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions