Passing Vec of Arc<Mutex>

I want to pass a vector of Mutexes into a thread. Each Mutex represents a file lock.

So far I have this: It does not compile of course. I am stuck on the fn argument for passing the vector "vecmtx". What is the appropriate type of this vector for the fn call?

use std::sync::Arc;
use std::cell::RefCell;
use std::sync::Mutex;



fn main() {


   let data = Arc::new(Mutex::new(0));
  let mut vecmtx  = Vec::new();
    vecmtx.push(data);


}

fn test_mtx(mutex_vec : Vec<Arc>) {
}

I would say Vec<Arc<Mutex>>.

That produces:

error[E0107]: missing generics for struct `Mutex`
  --> src/main.rs:20:33
   |
20 | fn test_mtx(mutex_vec : Vec<Arc<Mutex>>) {
   |                                 ^^^^^ expected 1 generic argument
   |

I don't think you got what I said: you must put the type as Vec<Arc<Mutex>> not Vec<Arc>.

The Mutex bit needs to have a generic to indicate what it holds. When they said Vec<Arc<Mutex>> it was intended that you have a list of atomic reference counted pointers to mutexes containing something.

If you are passing files around, then the full type will be Vec<Arc<Mutex<std::fs::File>>>.

2 Likes

That did it! Ok makes full sense to me now.

fn main() {

///TODO REMOVE TEST
let data = Arc::new(Mutex::new(0));

let mut vecmtx  = Vec::new();
vecmtx.push(data);

}
// Vec<Arc<Mutexstd::fs::File>>.
"fn test_mtx(mutex_vec : Vec<Arc<Mutex>>)" {
}

1 Like