如何在 Rust 线​​程中使用克隆

How to use a clone in a Rust thread

在这个 rust 程序中,在 运行 函数中,我试图将“pair_clone”作为参数传递给两个线程,但我一直收到类型不匹配的错误?我以为我传递的是对,但它说我传递的是整数。

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");
}

你有两个主要错误

第一个:您正在使用对的名称作为循环索引。这使得 pair 成为编译器抱怨的整数。

第二种:你用的是一份,你需要两份,一份给生产者,一份给消费者


编辑后

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


请注意,我没有对代码质量给予任何关注。刚刚修复了编译错误。