Rust标准库中有几种包装类型:
std::cell模块中的单元格:Cell和RefCellRc和Arc.std::sync模块中的类型:Mutex或者AtomicBool例如据我了解,这些是包装器,提供了比简单参考更多的可能性.虽然我理解一些基础知识,但我看不到整体情况.
他们到底做了什么?细胞和参考计数家族是否提供正交或类似的特征?
我正在尝试并行化我的算法.这是我将如何用C++编写它的草图:
void thread_func(std::vector<int>& results, int threadid) {
results[threadid] = threadid;
}
std::vector<int> foo() {
std::vector<int> results(4);
for(int i = 0; i < 4; i++)
{
spawn_thread(thread_func, results, i);
}
join_threads();
return results;
}
Run Code Online (Sandbox Code Playgroud)
这里的要点是每个线程都有一个它不拥有的共享可变对象的引用.在Rust中,这似乎很难做到.我是否应该尝试将它拼凑在一起(我猜这里)Mutex,Cell或者&mut,我应该遵循更好的模式吗?
我一直在研究一个函数,它将使用Rust和线程将一堆文件从源复制到目标.我在线程共享迭代器时遇到了一些麻烦.我还不习惯借用系统:
extern crate libc;
extern crate num_cpus;
use libc::{c_char, size_t};
use std::thread;
use std::fs::copy;
fn python_str_array_2_str_vec<T, U, V>(_: T, _: U) -> V {
unimplemented!()
}
#[no_mangle]
pub extern "C" fn copyFiles(
sources: *const *const c_char,
destinies: *const *const c_char,
array_len: size_t,
) {
let src: Vec<&str> = python_str_array_2_str_vec(sources, array_len);
let dst: Vec<&str> = python_str_array_2_str_vec(destinies, array_len);
let mut iter = src.iter().zip(dst);
let num_threads = num_cpus::get();
let threads = (0..num_threads).map(|_| {
thread::spawn(|| while let Some((s, d)) = iter.next() {
copy(s, d); …Run Code Online (Sandbox Code Playgroud)