vorner / arc-swap

Support atomic operations on Arc itself
Apache License 2.0
777 stars 31 forks source link

how to implement a concurrent hashmap? #88

Closed lithbitren closed 1 year ago

lithbitren commented 1 year ago
use arc_swap::ArcSwap;
fn arc_swap_hashmap(map: HashMap<usize, usize>, getn: usize, setn: usize, workers: usize) {
    let map = Arc::new(ArcSwap::from_pointee(map));
    let start = Instant::now();
    let threads: Vec<_> = (0..workers)
        .map(|_| {
            let map = map.clone();
            thread::spawn(move || {
                for i in 0..getn / workers {
                    let _ = map.load().get(&i).unwrap();
                }
                for i in 0..setn / workers {
                    map.load().insert(i, i); // error[E0596]: cannot borrow data in an `Arc` as mutable
                }
            })
        }).collect();
    for thread in threads {
        thread.join().unwrap();
    }
    print!("arc_swap_hashmap: {:?}, ", start.elapsed());
}

How to modify this code so that it can be compiled

vorner commented 1 year ago

Hello

You seem to be missing the point / principle what arc-swap is and what it isn't. It in no way allows you to modify the „insides“. It only allows you to replace it as a whole.

So, you could do some of these:

As there's nothing that's an issue related to arc-swap itself, I'm going to close this… this isn't really supposed to be a „help with Rust borrow checker forum“.