How to share a HashMap between threads

Following @alice’s suggestions will make your current code work, but you might not see much performance improvement over a single-threaded solution: each thread needs to take the write lock for every character it wants to tally, so there isn’t a lot of chance for parallelism to happen. Consider having each thread build a temporary HashMap of counts, and then only add those totals to the main result after the local count is finished.

Another improvement would be to only construct the chars() iterator once per thread:

let local_input = all_input.clone();
thread::spawn( move ||
    for c in local_input.chars().skip(start).take(end-start) {
        /* ... */
    }
)

You’ll need to join() all of the worker threads to wait for them to finish, and then use Arc::try_unwrap() and RwLock::into_inner() to get the HashMap out to return.

4 Likes