简体   繁体   中英

How to use a clone in a Rust thread

In this rust program, inside the run function, I am trying to pass the "pair_clone" as a parameter for both threads but I keep getting a mismatched type error? I thought I was passing the pair but it says I'm passing an integer instead.

use std::sync::{Arc, Mutex, Condvar};
fn producer(pair: &(Mutex<bool>, Condvar), num_of_loops: u32) {
     let (mutex, cv) = pair;
    //prints "producing"    
    }

}

fn consumer(pair: &(Mutex<bool>, Condvar), num_of_loops: u32) {
let (mutex, cv) = pair;
//prints "consuming"
    }
}

pub fn run() {
    println!("Main::Begin");
    let num_of_loops = 5;
    let num_of_threads = 4;
    let mut array_of_threads = vec!();

    let pair = Arc ::new((Mutex::new(true), Condvar::new()));
    for pair in 0..num_of_threads {
        let pair_clone = pair.clone();
        array_of_threads.push(std::thread::spawn( move || producer(&pair_clone, num_of_loops)));
        array_of_threads.push(std::thread::spawn( move || consumer(&pair_clone, num_of_loops)));
    }

    for i in array_of_threads {
        i.join().unwrap();
    }    


    println!("Main::End");
}

You have two main errors

The first : you are using the name of the pair as the loop index. This makes pair be the integer the compiler complains about.

The second : you are using one copy while you need two, one for the producer and the other for the consumer


After Edit

use std::sync::{Arc, Mutex, Condvar};
fn producer(pair: &(Mutex<bool>, Condvar), num_of_loops: u32) {
    let (mutex, cv) = pair;
    //prints "producing"

}

fn consumer(pair: &(Mutex<bool>, Condvar), num_of_loops: u32) {
    let (mutex, cv) = pair;
//prints "consuming"
}

pub fn run() {
    println!("Main::Begin");
    let num_of_loops = 5;
    let num_of_threads = 4;
    let mut array_of_threads = vec![];

    let pair = Arc ::new((Mutex::new(true), Condvar::new()));
    for _ in 0..num_of_threads {
        let pair_clone1 = pair.clone();
        let pair_clone2 = pair.clone();
        array_of_threads.push(std::thread::spawn( move || producer(&pair_clone1, num_of_loops)));
        array_of_threads.push(std::thread::spawn( move || consumer(&pair_clone2, num_of_loops)));
    }

    for i in array_of_threads {
        i.join().unwrap();
    }


    println!("Main::End");
}

Demo


Note that I haven't given any attention to the code quality. just fixed the compile errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM