Concurrent access to vector from multiple threads using a mutex lock

前端 未结 1 608
南旧
南旧 2020-12-11 19:25

I\'m using an example provided by the Tokio library and attempting to have a vector of all the currently active TCP connections. Ultimately, I would like to be able to broad

相关标签:
1条回答
  • 2020-12-11 19:53

    You get the first error because of the move closure:

    let mut connections = Arc::new((Mutex::new(Vec::new())));
    thread::spawn(move || {
        let mut i = connections.lock().unwrap().len();
        ....
    }
    

    This actually moves the whole Arc, while you only want to move "a part" of it (that is, move it in such a way that the reference count is incremented, and that both threads can use it).

    To do this, we can use Arc::clone:

    let mut connections = Arc::new((Mutex::new(Vec::new())));
    let conn = connections.clone();
    thread::spawn(move || {
        let mut i = conn.lock().unwrap().len();
        ....
    }
    

    This way, the cloned Arc, conn, is moved into the closure, and the original Arc, connections, is not, and hence still usable.

    I'm not sure exactly what you are doing with your second error, but for the sake of simply counting the connections you do not need to push the entire thing.

    0 讨论(0)
提交回复
热议问题