繁体   English   中英

如何在 Rust 线程中使用克隆

[英]How to use a clone in a Rust thread

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

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成为编译器抱怨的 integer。

第二个:您使用一个副本,而您需要两个副本,一个用于生产者,另一个用于消费者


编辑后

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

演示


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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