Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to iterate over Arc Mutex

Consider the following code, I append each of my threads to a Vector in order to join them up to the main thread after I have spawned each thread, however I am not able to call iter() on my vector of JoinHandlers.

How can I go about doing this?

fn main() {
    let requests = Arc::new(Mutex::new(Vec::new()));
    let threads = Arc::new(Mutex::new(Vec::new()));

    for _x in 0..100 {
        println!("Spawning thread: {}", _x);

        let mut client = Client::new();
        let thread_items = requests.clone();

        let handle = thread::spawn(move || {
            for _y in 0..100 {
                println!("Firing requests: {}", _y);

                let start = time::precise_time_s();

                let _res = client.get("http://jacob.uk.com")
                    .header(Connection::close()) 
                    .send().unwrap();

                let end = time::precise_time_s();

                thread_items.lock().unwrap().push((Request::new(end-start)));
            }
        });

        threads.lock().unwrap().push((handle));
    }

    // src/main.rs:53:22: 53:30 error: type `alloc::arc::Arc<std::sync::mutex::Mutex<collections::vec::Vec<std::thread::JoinHandle<()>>>>` does not implement any method in scope named `unwrap`
    for t in threads.iter(){
        println!("Hello World");
    }
}
like image 323
Jacob Clark Avatar asked Dec 04 '25 23:12

Jacob Clark


1 Answers

First, you don't need threads to be contained in Arc in Mutex. You can keep it just Vec:

let mut threads = Vec::new();
...
threads.push(handle);

This is so because you don't share threads between, well, threads. You only access it from the main thread.

Second, if for some reason you do need to keep it in Arc (e.g. if your example does not reflect the actual structure of your program which is more complex), then you need to lock the mutex to obtain a reference to the contained vector, just as you do when pushing:

for t in threads.lock().unwrap().iter() {
    ...
}
like image 81
Vladimir Matveev Avatar answered Dec 06 '25 13:12

Vladimir Matveev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!