Skip to content

Arc types in Rust with a predefined number of instances

License

Notifications You must be signed in to change notification settings

sug0/static-arc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Static Arc

This Rust crate provides a construct similar to a std::sync::Arc, except the number of live instances throughout the whole program's lifetime is known a priori.

Example usage

use std::thread;
use std::sync::Mutex;
use std::collections::HashMap;

use static_arc::StaticArc;

struct SharedData {
    data: Mutex<HashMap<String, i32>>,
}

fn main() {
    let [thread_ptr, main_ptr] = StaticArc::new(SharedData {
        data: Mutex::new(HashMap::new()),
    }).unwrap();

    thread::spawn(move || {
        let mut data = thread_ptr.data.lock().unwrap();
        data.insert("x".into(), 1);
        data.insert("y".into(), 2);
        data.insert("z".into(), 3);
    });

    let data = recover(main_ptr);

    for (k, v) in data.iter() {
        println!("{}: {}", k, v);
    }
}

fn recover(arc: StaticArc<SharedData>) -> HashMap<String, i32> {
    let mut opt_arc = Some(arc);

    loop {
        let result = opt_arc
            .take()
            .unwrap()
            .try_into_inner_recover();

        match result {
            Ok(shared) => return shared.data.into_inner().unwrap(),
            Err(arc) => opt_arc = Some(arc),
        }
    }
}

About

Arc types in Rust with a predefined number of instances

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages