我的线程到达这些行的是什么?



我是Rust的新手,我正在尝试编写一个简单的程序,一旦用户提供路径和密码,就可以用AES加密文件。该代码创建与虚拟CPU数量一样多的线程,并加密新文件中特定路径中的每个文件,最后使用相同的名称+加密。

但由于一些我还不明白的特殊原因,即使没有错误或警告,程序的最后几行也永远不会到达。代码如下:


fn encrypt_file(
filepath: &str,
pass: &str,
) -> Result<(), io::Error> {
println!("The filepath: {}", filepath);
let text_vec = String::from_utf8_lossy(&fs::read(filepath).unwrap()).as_bytes().to_vec();
println!("File read complete:");
let mut encryptionPassword: String;
if pass.len() < 32 {
let length = 32 - pass.len();
let strr = (0..length).map(|_| "0").collect::<String>().to_owned();
encryptionPassword = format!("{}{}", pass, strr);
} else if pass.len() > 32 { 
encryptionPassword = String::from(&pass[..32]);
} else { 
encryptionPassword = String::from(pass);
}
println!("encryptionPassword: {:?}",&encryptionPassword);
let ciphertext = enc_file::encrypt_aes(text_vec, &encryptionPassword.as_str()).unwrap();

let enc = ".encrypted";
let dist = format!("{}{}", filepath, enc);
fs::write(&dist, &ciphertext)?;
println!("wrote");

let mut buffer = String::new();
File::open(&dist).unwrap().read_to_string(&mut buffer)?;
println!("file opened");
let decrypted = enc_file::decrypt_aes(buffer.into_bytes().to_vec(), encryptionPassword.as_str());
println!("Decrypted: {:?}",decrypted );
Ok(())
}

fn main() {
let matches = Command::new("Multithreaded encryptor")
.version("0.1.0")
.arg(Arg::new("password")
.short("p".parse().unwrap())
.long("password")
.takes_value(true)
.help("Encryption password"))
.arg(Arg::new("path")
.short("D".parse().unwrap())
.long("path") //Double quotes needed!
.takes_value(true)
.help("Path to files"))
.get_matches();
let pass = matches.value_of("password").unwrap_or_else(
|| { "null" }
); 
let path = matches.value_of("path").unwrap_or_else(
|| { process::exit(1); }
); 
println!("The password: {}", pass);
println!("The path: {}", path);

let thread_pool = ThreadPool::new(num_cpus::get()); //As many threads as virtual CPUs.

for entry in WalkDir::new(path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| !e.path().is_dir())
{
let filepath = entry.path().to_owned();
let a3 = pass.to_owned();
thread_pool.execute(move || {
encrypt_file(filepath.to_str().unwrap(), a3.as_str()).unwrap();
});
}
}

";println!("打开的文件"("行和下面的所有内容,到目前为止还没有到达一次,但并没有错误或警告。已成功创建加密文件,并且包括加密数据,但其下方似乎没有执行任何内容。

似乎也有一定程度的随机性,因为有时加密文件不包含数据,但这可能是底层文件系统的特点。。。

在Rust中,如果main()函数完成,无论是否有其他线程处于活动状态,程序都将终止。

作为main()中的最后一步,您需要等待提交到池中的未完成作业完成。您可以使用ThreadPool::join():进行此操作

thread_pool.join();

最新更新