2

Here is the code:

use std::collections::HashMap;
use std::thread;

type MAP = HashMap<String, String>;

fn handle_n_times(count: i32, map: &mut MAP) {
    for i in 0..count {
        thread::spawn(move || {
            map.insert(format!("key-{}", i), format!("value-{}", i));
        });
    }
}

fn main() {
    let mut map: MAP = MAP::new();
    handle_n_times(5, &mut map);
}

I cannot compile:

error[E0621]: explicit lifetime required in the type of `map`
 --> src/main.rs:8:9
  |
6 | fn handle_n_times(count: i32, map: &mut MAP) {
  |                                    -------- help: add explicit lifetime `'static` to the type of `map`: `&'static mut std::collections::HashMap<std::string::String, std::string::String>`
7 |     for i in 0..count {
8 |         thread::spawn(move || {
  |         ^^^^^^^^^^^^^ lifetime `'static` required

The hint it provides (add a &'static) is not helpful.

Question 1: How to make this code work?

Question 2: After 1 solved, I want to use std::sync::Arc to make map thread-safe, what's the Rust way to do it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mitnk
  • 3,127
  • 2
  • 21
  • 28

1 Answers1

3

Question 1:

It is not thread safe to share variables into new threads. In Rust you can not compile this code. You can make the code work via using Arc<Mutex<Map>>

Question 2:

You need to change method signature as follows:

 handle_n_times(count: i32, arc_map: Arc<Mutex<Map>>)

In case you are moving ownership in your thread::spawn, you need to clone Arc value just before sending it to other thread with

 let clone_arc = arc_map.clone();

When you want to insert an item to the map you need to get reference from the Arc<Mutex> via lock and unwrap:

let map = clone_arc.lock().unwrap();

After that you can call map.insert with no explicit lifetime requirements.

Here is the full working code as an example

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68