我正在将我的 C++ 国际象棋引擎移植到 Rust 中。我有一个在搜索线程之间共享的大哈希表,并且在 C++ 版本中该表是无锁的;没有用于共享读/写访问的互斥体。这是the theory ,如果您有兴趣。
在此代码的 Rust 版本中,它工作正常,但使用了 Mutex
:
let shared_hash = Arc::new(Mutex::new(new_hash()));
for _ in 0..n_cpu {
println!("start thread");
let my_hash = shared_hash.clone();
thread_pool.push(thread::spawn(move || {
let mut my_hash = my_hash.lock().unwrap();
let mut search_engine = SearchEngine::new();
search_engine.search(&mut myhash);
}));
}
for i in thread_pool {
let _ = i.join();
}
如何在没有互斥体的情况下在线程之间共享表?
最佳答案
实际上很简单:如果底层结构已经同步
,则不需要互斥体
。
在您的情况下,例如原子结构数组就可以工作。您可以找到 Rust 的可用原子 here .
关于multithreading - Rust 中的线程之间共享无锁资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704003/